How to insert only distinct values to a MySQL table? - javascript

I'm using Google Apps Script to update a MySQL table from Google Cloud SQL and I don't want to insert duplicate values, for example:
If I have the following table with a record
+----+--------+-----------+-------+
| id | name | address | phone |
+----+--------+-----------+-------+
| 1 | John | Somewhere | 022 |
+----+--------+-----------+-------+
| 2 | Snow | North | 023 |
+----+--------+-----------+-------+
Then I should not be able to execute a query that inserts a new record where
name=John,
address=Somewhere,
phone=022
or
name=Snow,
address=North,
phone=023
This is my current code that inserts new records to the database:
var stmt = conn.prepareStatement('INSERT INTO entries '
+ '(name, address, phone) values (?, ?, ?)');
stmt.setString(1, "John");
stmt.setString(2, "Snow");
stmt.setString(3, 022);
stmt.execute();

Related

ASCII Table does not format as I want it to be

I'm making a discord bot using MySQL, the database stores some usernames and passwords. I fetch the data from the table in MySQL to format it in an ASCII table. The expected output was to be like the image below. (edited it to look better)
.------------------------------------------------.
| Username | Password |
|----------------------|-------------------------|
| amonggers | no |
| no username for u | no |
| not even this one | no |
| no | no |
'------------------------------------------------'
But the bot forms the table like this.
.------------------------------------------------.
| Username | Password |
|----------------------|-------------------------|
| amonggers | no
|
| no username for u | no
|
| not even this one | no
|
| no | no |
'------------------------------------------------'
Edit: I also console logged it and the output is a bit better than the discord bot one.
.------------------------------------------------.
| Username | Password |
|----------------------|-------------------------|
|amonggers | no
|no username for u | no
|not even this one | no
| no | no |
'------------------------------------------------'
[![Console Log created][3]][3]
Heres the command code
client.on("messageCreate", async (message) => {
if (message.content.toLowerCase().startsWith("=list")) {
connection.query("SELECT * FROM rbinfo", (err, results) => {
if (err) {
console.log(err)
}
const ascii = require('ascii-table');
var table = new ascii()
table.setHeading('Username', 'Password')
results.forEach(ok => table.addRow(ok.Username, ok.Password))
});
}
});
Any help at all is appreciated, thanks.

Issue with inserting data into MariaDB using NodeJS

const mariadb = require('mariadb/callback');
const connection = mariadb.createConnection({
host : 'localhost',
user : 'tudublin',
password : 'Tudublin#2020',
database : 'IOT',
timezone: 'Europe/Dublin',
});
connection.connect(err => {
if (err) {
console.log("not connected due to error: " + err);
} else {
console.log("connected ! connection id is " + connection.threadId);
}
});
connection.query("INSERT INTO observations VALUES (?, ?, ?, ?)", [2, 20, "oC", Date.now()], (err, result) => {
if (err) throw err;
console.log(result);
//log : { affectedRows: 1, insertId: 1, warningStatus: 0 }
}
);
MariaDB [IOT]> describe observations;
+-----------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+----------------+
| data_id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| sensor_id | int(10) unsigned | NO | MUL | NULL | |
| temp | int(11) | YES | | NULL | |
| temp_unit | varchar(30) | YES | | NULL | |
| dt_added | datetime | YES | | NULL | |
+-----------+------------------+------+-----+---------+----------------+
5 rows in set (0.003 sec)
Hi,
I am trying to insert data into my observations table. But it keeps displaying the error:
code: 'ER_WRONG_VALUE_COUNT_ON_ROW'
I created the table using the below command
CREATE TABLE observations (data_id INT unsigned not null auto_increment primary key,sensor_id INT unsigned not null, temp int, temp_unit VARCHAR(30), dt_added DATETIME);
&
ALTER TABLE observations ADD FOREIGN KEY (sensor_id) REFERENCES sensors(sensor_id);
Which I thought the way it's set up would be fine as I am only entering in 4 values and the other one being the data_id which is set as a primary key and auto_increments. Would anyone have any idea on why it shows the above error?
Thanks!
In INSERT INTO observations VALUES (?, ?, ?, ?) you omit the column names associated with the values, due to that you need to provide values for all columns, also the primary key (even so it has auto increment).
You generally should not rely only on the column order when inserting values but use the corresponding column names. This will prevent you from future problems in case the column order changes for some reason and allows you to omit the data_id column:
INSERT INTO `observations`(`sensor_id`, `temp`, `temp_unit`, `dt_added`) VALUES (?,?,?,?)

Inserting values into a table and delete rows based on a condition using merge in snowflake

I have a table with DBName, SCName, Number. I wrote a procedure that inserts the DBName, SCName into the table and deletes a row when a Number is 0. I used merge to avoid duplicates and insert based on the condition but I don't understand how to delete a row when a Number=0.
------------------------
|DBName| SCName| Number|
| DB1 | SC1 | 1 |
| DB2 | SC2 | 0 | <-- Need to delete row
| DB2 | SC3 | 2 |
| DB2 | SC1 | 4 |
| DB3 | SC4 | 0 | <-- Need to delete row
------------------------
Here is my Procedure:
CREATE TABLE TABL(DBName VARCHAR, SCName VARCHAR); // creating table
CREATE OR REPLACE PROCEDURE repo(DB VARCHAR,SC VARCHAR)
RETURNS string
LANGUAGE JAVASCRIPT
AS
$$
//inserting values into table using merge
//if values are already present and Number = 0 then I need to delete row
var sql_command = `merge into TABL as t
using (SELECT :1 as database,:2 as schema) as s
on t.DBName = s.database
and t.SCName = s.schema
when matched then update
set t.DBName = t.DBName
when not matched then insert
(DBName, SCName) VALUES (:1,:2)`;
snowflake.execute({sqlText: sql_command, binds: [DB, SC]});
return 'success';
$$;
I didn't understand in which case (MATCHED / NOT MATCHED) the rows with '0' should be deleted from the target table.
But in general you have only can use DELETE in the MATCH-case:
when matched and number=0 then delete
It is important to avoid a nondeterministic result for the merge (see link below under "Duplicate Join Behavior"). Solution therefor is to also add "and number!=0" to your "when matched then update"-clause.
More infos: https://docs.snowflake.com/en/sql-reference/sql/merge.html
EDIT: I posted wrong information. For MATCH you can Delete and Update, for NOT MATCH you can INSERT.

Querying existing linked tables from mySQL in a graphql resolver?

Currently, I'm connecting to database and creating tables with Sequelize, and doing the rest with Graphql, making the schemas, queries and resolvers.
I seem to have hit a wall with how to ask for the data from these 3 linked tables:
CITY CompLocations CompIssue
| id | | locationID | compID | | locationID | issueLevel |
|*1* | -----> | 1 | 45 | ------> | 45 | *5*
| 2 | | 2 | 203 | | 203 | 3
I just need to retrieve all the CompIssue.issueLevel's associated with CITY.id, via this existing relation/association.
Im looking at associations and querying in Sequelize's API. How would one query the above within a Grapql/Apollo resolver function?
I know this is an older question but I hit on a similar issue recently. In my case I am using seriate to connect to an MSSQL server from Nodejs and wanted to create the GraphQL schema dynamically based on the DB design (following the linked fields and such to create the sub-queries). Going this route I got the sql:
`SELECT
BASE_TABLE = t.TABLE_NAME,
BASE_COLUMN = col.COLUMN_NAME,
DATA_TYPE,
LEN_PRECISION = COALESCE(
CHARACTER_MAXIMUM_LENGTH,
numeric_precision,
datetime_precision
),
LINKED_TABLE = keys.Data_Table,
LINKED_COLUMN = keys.Data_Column
FROM INFORMATION_SCHEMA.TABLES t INNER JOIN
INFORMATION_SCHEMA.COLUMNS col ON
t.TABLE_NAME = col.TABLE_NAME LEFT JOIN
( SELECT
Base_Table = FK.TABLE_NAME,
Base_Column = CU.COLUMN_NAME,
Data_Table = PK.TABLE_NAME,
Data_Column = PT.COLUMN_NAME,
Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON
C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON
C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON
C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME INNER JOIN
( SELECT
i1.TABLE_NAME,
i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON
i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON
PT.TABLE_NAME = PK.TABLE_NAME
) keys ON
keys.Base_Table = t.TABLE_NAME AND
keys.Base_Column = col.COLUMN_NAME
WHERE t.TABLE_TYPE = 'BASE TABLE'`
This may not be the most elegant, and is likely to hit some performance issues on larger databases, but it worked well for me. The final dataset will give you the list of table/column pairs with any links to other table/column pairs from your database design.
From this dataset it should be "trivial" to check for the links and create any sub-queries you need in your GraphQL setup.

How to auto-update date field on firebase using ng-grid

I have a date field (called: lastUpdate) on a firebase db.
How could I update that field using ng-grid on change from another field (say a separte field called: notes)?
Im using the following code to update my records on edit:
var cellEditableTemplate = "<input ng-class=\"'colt' + col.index\"
ng-input=\"COL_FIELD\" ng-model=\"COL_FIELD\"
ng-change=\"updateEntity(col,row)\"/>"
$scope.updateEntity = function (col, row) {
$scope.dblogs.$save(row.entity.$id);
};
Posted Below is my sample db being used:
uniqueIDajsdljfasdjfajsdf;jasdj
|
|
--->ticket
| |
| -->completed: true
| |
| -->dateUpdated: "(last activity date/time)"
| |
| -->notes: "need to update logger code today!"
|
---->username: "vr"

Categories