Unable to insert data into mysql in node - mysql

Trying to insert data into mysql with 'INSERT INTO users SET ?', I get 500 error in front end. data is reaching the server but unable to insert into database. Tried even 'INSERT INTO users VALUES ?' but still fails. i'm able to retrieve the data from the database('SELECT * FROM users') but not inserting it.
router.post('/userstuff', function(req, res, next) {
var eachuser = {
name: req.body.name,
age: req.body.age
};
connection.query('INSERT INTO users SET ?',eachuser, function(err, rows){
if(err) console.log('Error selecting: %s ', err);
console.log(rows)
});
});
edit: added the schema:
use 02sqldb;
CREATE TABLE IF NOT EXISTS users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(30),
age int(2)
);

And what if you try to first do a dummy query. I don't know for sure you can simply put "?" to insert a value without giving a column like
'INSERT INTO table_name (column1,column2,column3,...)
VALUES ('?','?','?',...)'
If it still isn't working you know it's something else.

Related

How to create a Nodejs MySQL execute query for values that might not exist

I'm inserting values into a MySQL database using Nodejs mysql2 library.
Here is an example of a prepared statement:
await conn.execute(
'INSERT INTO Friends (id, user, name, gender) VALUES (UUID(), ?, ?, ?)',
[ user, body.name, body.gender ]
);
How can I achieve the above if sometimes the body.gender value is not set? I want several attributes in the http request to be optional and insert all allowed values that have been sent in the http request into the database.
The above code gives an error if I leave body.gender out of the http request.
If there is no some data in body or not sending some data from the client to register in the database, you have to put a null value for that row in that column. You can use this JavaScript feature to do this:
await conn.execute(
'INSERT INTO Friends (id, user, name, gender) VALUES (UUID(), ?, ?, ?)',
[ user || null, body.name || null, body.gender || null ]
);
Using this possibility, in the absence of any of the data sent in the body, its value is undefined and the value of null is placed in the query.

SQL Check if table exists then Create Table & Insert into same query

Tried This Code But it gives "ER_PARSE_ERROR"
Err Description: "sqlMessage": "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Insert values ('Bitcoin')' at line 1"
var query = "CREATE TABLE IF NOT EXISTS projects (project_name VARCHAR(10)) Insert values ('" + projectName + "')";
I want to Insert a new Project in the Projects Table, create the table if it does not exists and insert the record, I can write multiple queries for this work and check response if success then proceed with the next query but I am looking for a query which does all the work concatenating multiple queries in itself.
Note: I am using mysql module in Nodejs
The process should work synchronously one after the other, when a user sends a post request to the route '/add_project' with data in body "project_name":"project1" then the server inserts the record in the mysql table projects but it generates err "No such Table " if that was the first record.
I want it to work synchronously first by creating the table if not exists and then inserting the record.
Edit: Added screenshot for #Nick suggestion
You could use CREATE TABLE ... SELECT syntax:
var query = "CREATE TABLE IF NOT EXISTS projects (project_name VARCHAR(10)) SELECT '" + projectName + "' AS project_name";
Demo on rextester
Working Code But I need to get less complicated code without much error handling:
app.post('/add_project_to_database',function(req,res){
var projectName = req.body.project_name;
//CHECK IF PROJECT EXISTS
var query = "Select project_name from projects where project_name = '" + projectName + "'";
return res.send('Project Already Exists!');
//INSERTING PROJECT
// var query = "CREATE TABLE IF NOT EXISTS projects (project_name VARCHAR(10)) Insert values ('" + projectName + "')";
var query = "Insert into projects(project_name) values ('" + projectName + "')";
con.query(query, function(err, result){
if(err){
var query_create = "CREATE TABLE IF NOT EXISTS projects (project_name VARCHAR(10))";
con.query(query_create,function(error,res_create){
if(error){
console.log(error);
res.send(error);
}
else{
console.log("TABlE CREATED");
con.query(query,function(error_insert,response){
if(error_insert){
console.log(error_insert);
res.send(error_insert);
}
else{
console.log("RECORD INSERTED SUCCESSFULLY !");
}
});
}
});
}else{
res.send("Successfully Inserted Project");
}
});
});

How to know if MySql's conditional INSERT worked?

With a conditional Insert, I want to know if a row was inserted or if overlap was found.
I have a query that inserts a request into the database if it doesn't overlap with any existing entry. The query works, but how do I know if there's been an collision? The query just executes successfully. Here is my query:
INSERT INTO requests(id, start_time, end_time)
SELECT NULL, 1463631640671,1463636731000,
FROM Dual
WHERE NOT EXISTS (
SELECT * FROM requests
WHERE
start_time < 1463638531000 AND
end_time > 1463636731000
)
For your information. I'm doing this inside Node.js with the mysql package.
and the code looks like this, and it returns 'SUCCESS' every time.
var queryString = "INSERT INTO requests(id, start_time, end_time..."
connection.query(queryString, function(error, results, fields) {
if (!error) {
console.log('SUCCESS!');
}
else {
console.log('Insert into requests unsuccessful.');
console.log('ERROR: ' + error);
}
});
you can inspect results.insertId and see if you have something in it.

Serializable transactions using mysql and node.js

I am having problems with transactions using node.js and mysql. The problem is that my transactions do not run in isolation, even if I set the isolation level to 'serializable'.
I set up the following minimal example to exemplify my problem. I am using a single table with two collumns (id, val):
CREATE TABLE `A` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`val` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `A` (`id`, `val`) VALUES (1,0);
Note that I am unsing InnoDB table type because it supports transactions.
My node.js program just reads the value from the single row in table A, and increments it using an update statement. The select statement uses the FOR UPDATE modifier to obtain a lock on the row. The two sql statement are wrapped into a transaction, and I execute 10 of these transactions in a for loop:
var orm = require("orm");
orm.connect("mysql://root#localhost/test", function (err, db) {
db.driver.execQuery("SET GLOBAL tx_isolation='SERIALIZABLE';", function (err, data) {
for (var i = 0; i < 10; i++) {
db.driver.execQuery("START TRANSACTION;", function (err, data) {
db.driver.execQuery("SELECT * FROM A FOR UPDATE;", function (err, data) {
var value = data[0].val
console.log('reading value: ',value)
db.driver.execQuery("UPDATE A SET val="+value+"+1 WHERE id=1", function (err, data) {
console.log('writing value: ', value+1)
db.driver.execQuery("COMMIT;", function (err, data) {})
})
})
})
}
})
})
I would expect that after running this code, the value stored in the table A is incremented by 10. However, it is just incremented by 1.
To understand what's going on I added printouts to the code. I would expect to see printouts
reading value 0
writing value 1
reading value 1
writing value 2
...
However I get the printouts
reading value 0
reading value 0
...
writing value 1
writing value 1
...
One way to fix the problem is to establish a new db connection for each transaction, but I'd prefer not to do that for performance reasons.
Can someone explain what is going on, and how I can change the above into a working example for transactions in node.js?
Ok, we found a solution using the node-mysql-transaction package (see code below).
var mysql = require('mysql');
var transaction = require('node-mysql-transaction');
var trCon = transaction({
connection: [mysql.createConnection,{
host : 'localhost',
database : 'test',
user : 'root',
password : 'root',
}],
dynamicConnection: 32,
idleConnectionCutoffTime: 1000,
timeout:600
});
for(var i=0;i<10;i++) {
trCon.set(function(err, safeCon){
safeCon.query('SELECT * FROM A FOR UPDATE;',[],function(err,result){
if (err) safeCon.rollback()
var val = result[0].val
val += 1
safeCon.query('UPDATE A SET val='+val,[],function(err,result){
if (err) safeCon.rollback(err)
else safeCon.commit();
})
})
})
}

How to update multiple columns using array of datas with a prepared statement?

I have 2 arrays :
columns = ['column1', 'column2'];
data = ['data1', 'data2'];
I'd like to update the table using a prepared query:
conn.query('UPDATE table SET ?? = ? WHERE id = ?', [columns, data, id],
function(err, info){
Excepted sql query :
UPDATE table SET column1 = 'data1', column2 = 'data2' WHERE id = 10
But I get something that looks like :
UPDATE table SET 'column1', 'column2' = 'data1', 'data2' WHERE id = 10
This feature works well for select or insert but it seems not working for update queries. Any thoughts on how I can get this work ?
From node-mysql docs, about escaping query values, we have this:
Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
, so it won't work the way you expect.
But, in the docs we also have this:
Objects are turned into key = 'val' pairs. Nested objects are cast to strings.
with an example:
var post = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
// Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
So, in order to do what you want, the best option IMO, is to convert your arrays into an object like:
{
column1: 'data1',
column2: 'data2'
}
Just to clarify, since after Googling for ages I didn't find an exact example to show what I was looking for. Here is the code which hopefully is what Bobby Shark found out, since I don't think 'SET ??' works.
To UPDATE multiple columns (but not necessarily all) for one row, without typing up every column in the query, but passing an object of {column_name1: 'new_foo', column_name2: 'new_bar', column_name2: 'new_baz'}
(using body-parser to get object of form data)
var blog = req.body.blog; // object as described above
var sql = "UPDATE blog SET ? WHERE id = ?";
connection.query(sql, [blog, req.params.id], function(err, updatedBlog){
if(err){
console.log(err);
} else {
res.redirect("/blogs/" + req.params.id);
}
});
This post by Bala Clark helped (though we've read it in the docs 10 times!). Hope this helps to see example code of object with multiple column updates (name/value pairs). Again found no specific examples in many sites.