nodejs mysql query doesn - mysql

I want to check if some date exist in a table, if not I want to insert it. I have done this in other project and there it works but now i don't know why it doesn't work.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '',
user : '',
password : '',
database : ''
});
[..]
connection.query('SELECT id FROM users [...]', function(err, results) {
if (err) {
throw err;
} else if (results.length==1) {
callback(null, results[0].id);
} else {
console.log('before insert');
connection.query('INSERT INTO users SET ?', user, function(err, result) {
console.log('insert');
if (err) throw err;
});
}
});
The query with INSERT doesn't work, but if i get that query out of the SELECT query then it works.
Doesn't matter if it is INSERT or other query.
In console I only see: 'before insert' and no error.
This query it's in a loop.

You have syntax error in insert statement, it has to be:
connection.query('INSERT INTO users (`id`) VALUES (?)', user, function(err, result) {
console.log('insert');
if (err) throw err;
});
You could also optimise the code to run a single query only, using INSERT IGNORE syntax. If record already exists, MySQL will just ignore the insert, without giving any errors. But your field id has to be set as primary key.
Optimised, the code will look like:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '',
user : '',
password : '',
database : ''
});
[..]
connection.query('INSERT IGNORE INTO users (`id`) VALUES (?)', user, function(err, results) {
if (err) {
throw err;
} else {
callback(null, user);
}
});

Related

errno: 1064, sqlState: '42000', sqlMessage: "You have an error in your SQL syntax; [duplicate]

I'm using nodejs 10.26 + express 3.5 + node-mysql 2.1.1 +
MySQL-Server Version: 5.6.16.
I got 4 DELETE's and want only 1 Database Request, so i connected the DELETE commands with a ";"... but it fails always.
var sql_string = "DELETE FROM user_tables WHERE name = 'Testbase';";
sql_string += "DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';";
sql_string += "DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase';";
sql_string += "DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase';";
connection.query(sql_string, function(err, rows, fields) {
if (err) throw err;
res.send('true');
});
It throws this error:
Error: ER_PARSE_ERROR: 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 'DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';DELETE FR' at line 1
But if i paste this SQL in PhpMyAdmin it is always successful...
If i write it in single query's its succeed, too.
connection.query("DELETE FROM user_tables WHERE name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
res.send('true');
});
});
});
});
Thanks for help!
I guess you are using node-mysql. (but should also work for node-mysql2)
The docs says:
Support for multiple statements is disabled for security reasons (it
allows for SQL injection attacks if values are not properly escaped).
Multiple statement queries
To use this feature you have to enable it for your connection:
var connection = mysql.createConnection({multipleStatements: true});
Once enabled, you can execute queries with multiple statements by separating each statement with a semi-colon ;. Result will be an array for each statement.
Example
connection.query('SELECT ?; SELECT ?', [1, 2], function(err, results) {
if (err) throw err;
// `results` is an array with one element for every statement in the query:
console.log(results[0]); // [{1: 1}]
console.log(results[1]); // [{2: 2}]
});
So if you have enabled the multipleStatements, your first code should work.
Using "multiplestatements: true" like shown below worked for me
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: '',
multipleStatements: true
});
connection.connect();
var sql = "CREATE TABLE test(id INT DEFAULT 1, name VARCHAR(50));ALTER TABLE test ADD age VARCHAR(10);";
connection.query(sql, function(error, results, fields) {
if (error) {
throw error;
}
});
To Fetch Data from DB(SQL), the following function would work accurately
router.get('/', function messageFunction(req, res){
//res.send('Hi Dear Rasikh, Welcome to Test Page.') //=> One Way
dbConn.query('SELECT COUNT(name) as counted, name, last_name, phone, email from students',
function (err, rows, fields) { // another Way
if (err) throw err
dbConn.query('SELECT name, author from books',
function (err, rowsBook, fields) { // another Way
if (err) throw err
// console.log('The counted is: ', rows[0].counted); //=> Display in console
// res.send('Hi Dear Rasikh, Welcome to Test Page.'+ rows[0].counted) //=> Display in blank page
res.render('main/index',{data:rows, myData:rowsBook});
})
});
});

Keep getting an error when trying to get the output from MySQL using Node JS [duplicate]

I'm using nodejs 10.26 + express 3.5 + node-mysql 2.1.1 +
MySQL-Server Version: 5.6.16.
I got 4 DELETE's and want only 1 Database Request, so i connected the DELETE commands with a ";"... but it fails always.
var sql_string = "DELETE FROM user_tables WHERE name = 'Testbase';";
sql_string += "DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';";
sql_string += "DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase';";
sql_string += "DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase';";
connection.query(sql_string, function(err, rows, fields) {
if (err) throw err;
res.send('true');
});
It throws this error:
Error: ER_PARSE_ERROR: 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 'DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';DELETE FR' at line 1
But if i paste this SQL in PhpMyAdmin it is always successful...
If i write it in single query's its succeed, too.
connection.query("DELETE FROM user_tables WHERE name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
res.send('true');
});
});
});
});
Thanks for help!
I guess you are using node-mysql. (but should also work for node-mysql2)
The docs says:
Support for multiple statements is disabled for security reasons (it
allows for SQL injection attacks if values are not properly escaped).
Multiple statement queries
To use this feature you have to enable it for your connection:
var connection = mysql.createConnection({multipleStatements: true});
Once enabled, you can execute queries with multiple statements by separating each statement with a semi-colon ;. Result will be an array for each statement.
Example
connection.query('SELECT ?; SELECT ?', [1, 2], function(err, results) {
if (err) throw err;
// `results` is an array with one element for every statement in the query:
console.log(results[0]); // [{1: 1}]
console.log(results[1]); // [{2: 2}]
});
So if you have enabled the multipleStatements, your first code should work.
Using "multiplestatements: true" like shown below worked for me
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: '',
multipleStatements: true
});
connection.connect();
var sql = "CREATE TABLE test(id INT DEFAULT 1, name VARCHAR(50));ALTER TABLE test ADD age VARCHAR(10);";
connection.query(sql, function(error, results, fields) {
if (error) {
throw error;
}
});
To Fetch Data from DB(SQL), the following function would work accurately
router.get('/', function messageFunction(req, res){
//res.send('Hi Dear Rasikh, Welcome to Test Page.') //=> One Way
dbConn.query('SELECT COUNT(name) as counted, name, last_name, phone, email from students',
function (err, rows, fields) { // another Way
if (err) throw err
dbConn.query('SELECT name, author from books',
function (err, rowsBook, fields) { // another Way
if (err) throw err
// console.log('The counted is: ', rows[0].counted); //=> Display in console
// res.send('Hi Dear Rasikh, Welcome to Test Page.'+ rows[0].counted) //=> Display in blank page
res.render('main/index',{data:rows, myData:rowsBook});
})
});
});

Node.js, discord.js & MySQL - ER_NO_SUCH_TABLE: Table 'NAME' doesn't exist

Just started coding a discord bot 2 days ago and I'm now stuck here.
The error I get: ER_NO_SUCH_TABLE: Table 'mariobot.522488285910663201' doesn't exist
Part of code that has to do with this:
con.query(`SELECT * FROM ??`, [targetUserId], (err, result, fields) => {
if (err) {
con.query(
`CREATE TABLE IF NOT EXISTS ?? (userName varchar(255),positiveVouches int(10),negativeVouches int(10),totalVouches int(10),createdAt timestamp)`,
[targetUserId],
function (err, result) {
if (err) throw err;
console.log(`Table for ${userName} successfully created.`);
}
);
message.react("✅");
message.reply(`you successfully registered.`);
var sql = mysql.format(
"INSERT INTO ?? SET ? = ?, positiveVouches = 0,negativeVouches = 0,totalVouches = 0,createdAt = ?",
[targetUserId, "userName", userName, dformat]
);
con.query(sql, function (error, results, fields) {
console.log(sql);
if (err) {
throw err;
}
});
console.log(`Row for ${userName} successfully added.`);
} else {
console.log(
`${userName} tried to register again but a table already` + ` exists`.red
);
message.react("❎");
message.reply(`you are already registered.`);
}
});
The table exists in the database so I don't know what really causes it.
DATABASE TABLE IMAGE LINK
The issue is that while the CREATE TABLE statement is run, the following code is not done inside its callback. This means that while the statement is running, the code after it (message.react() etc.) is ran before the CREATE TABLE statement finishes. The same issue exists with the later con.query.
To fix this, move your code inside the callback which runs after the CREATE TABLE is finished:
con.query(`SELECT * FROM ??`, [targetUserId], (err, result, fields) => {
if (err) {
con.query(
`CREATE TABLE IF NOT EXISTS ?? (userName varchar(255),positiveVouches int(10),negativeVouches int(10),totalVouches int(10),createdAt timestamp)`,
[targetUserId],
function (err, result) {
if (err) throw err;
console.log(`Table for ${userName} successfully created.`);
message.react("✅");
message.reply(`you successfully registered.`);
var sql = mysql.format(
"INSERT INTO ?? SET ? = ?, positiveVouches = 0,negativeVouches = 0,totalVouches = 0,createdAt = ?",
[targetUserId, "userName", userName, dformat]
);
con.query(sql, function (error, results, fields) {
console.log(sql);
if (err) {
throw err;
}
console.log(`Row for ${userName} successfully added.`);
});
}
);
} else {
console.log(
`${userName} tried to register again but a table already` + ` exists`.red
);
message.react("❎");
message.reply(`you are already registered.`);
}
});

mysql.connect never returns

const mysql = require('mysql');
const dbCon = mysql.createConnection({
host: "localhost",
user: "mainUser",
password: "pa55",
database: "testDB"
});
dbCon.connect(function (err) {
if (err) throw err;
console.log("Connected to DB");
});
When I run it, I see the "Connected to DB" log but the program never finishes or exits, like it's waiting for something.
Let's try to get the code below and save this to 'dbConnect.js' file and then run node-command:
> node dbConnect.js
you will see the result.
const mysql = require('mysql');
const dbCon = mysql.createConnection({
host: "localhost",
user: "mainUser",
password: "pa55",
database: "testDB"
});
dbCon.connect(function(err) {
if (err) {
return console.log(err.message);
}
console.log('Connected to the MySQL server.');
});
let dbCreateQuery = `
create table if not exists users(
id int primary key auto_increment,
first_name varchar(255)not null,
last_name varchar(255)not null);
`;
let dbInsertQuery = `
insert into users (first_name, last_name)
values ('john', 'smith');
insert into users (first_name, last_name)
values ('jane', 'smith');
`;
let dbSelectQuery = `
select *
from users
`;
//test of create query execute
dbCon.query(
dbCreateQuery,
function(err, results, fields) {
if (err) {
console.log(err.message); //execution error
}
else {
console.log('Table "users" has been created';
}
});
//test of insert query execute
dbCon.query(
dbInsertQuery,
function(err, results, fields) {
if (err) {
console.log(err.message); //execution error
}
else {
console.log('Table "users" has been filled';
}
});
//test of select query execute
dbCon.query(
dbSelectQuery,
function(err, results, fields) {
if (err) {
console.log(err.message);
}
else {
console.log('Data rows from table "users" has been extracted';
console.log(results); // data rows
console.log(fields); // meta of fields
}
});
/*
Also, recommended use 'end()' method for closing connection to database after running operations.
*/
dbCon.end(function(err) {
if (err) {
return console.log(err.message);
}
console.log('Close the MySQL server connection.');
});
/*
Then use 'destroy()' method for close connection immediately, it's
guarantees that no more callbacks or events will be triggered for the connection,
i.e. method does not take any callback argument like the end() method.
*/
dbCon.destroy();

MYSQL syntax error while running query in nodejs . Works fine on mysql workbench [duplicate]

I'm using nodejs 10.26 + express 3.5 + node-mysql 2.1.1 +
MySQL-Server Version: 5.6.16.
I got 4 DELETE's and want only 1 Database Request, so i connected the DELETE commands with a ";"... but it fails always.
var sql_string = "DELETE FROM user_tables WHERE name = 'Testbase';";
sql_string += "DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';";
sql_string += "DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase';";
sql_string += "DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase';";
connection.query(sql_string, function(err, rows, fields) {
if (err) throw err;
res.send('true');
});
It throws this error:
Error: ER_PARSE_ERROR: 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 'DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';DELETE FR' at line 1
But if i paste this SQL in PhpMyAdmin it is always successful...
If i write it in single query's its succeed, too.
connection.query("DELETE FROM user_tables WHERE name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
res.send('true');
});
});
});
});
Thanks for help!
I guess you are using node-mysql. (but should also work for node-mysql2)
The docs says:
Support for multiple statements is disabled for security reasons (it
allows for SQL injection attacks if values are not properly escaped).
Multiple statement queries
To use this feature you have to enable it for your connection:
var connection = mysql.createConnection({multipleStatements: true});
Once enabled, you can execute queries with multiple statements by separating each statement with a semi-colon ;. Result will be an array for each statement.
Example
connection.query('SELECT ?; SELECT ?', [1, 2], function(err, results) {
if (err) throw err;
// `results` is an array with one element for every statement in the query:
console.log(results[0]); // [{1: 1}]
console.log(results[1]); // [{2: 2}]
});
So if you have enabled the multipleStatements, your first code should work.
Using "multiplestatements: true" like shown below worked for me
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: '',
multipleStatements: true
});
connection.connect();
var sql = "CREATE TABLE test(id INT DEFAULT 1, name VARCHAR(50));ALTER TABLE test ADD age VARCHAR(10);";
connection.query(sql, function(error, results, fields) {
if (error) {
throw error;
}
});
To Fetch Data from DB(SQL), the following function would work accurately
router.get('/', function messageFunction(req, res){
//res.send('Hi Dear Rasikh, Welcome to Test Page.') //=> One Way
dbConn.query('SELECT COUNT(name) as counted, name, last_name, phone, email from students',
function (err, rows, fields) { // another Way
if (err) throw err
dbConn.query('SELECT name, author from books',
function (err, rowsBook, fields) { // another Way
if (err) throw err
// console.log('The counted is: ', rows[0].counted); //=> Display in console
// res.send('Hi Dear Rasikh, Welcome to Test Page.'+ rows[0].counted) //=> Display in blank page
res.render('main/index',{data:rows, myData:rowsBook});
})
});
});