Building a massive query based on single query [duplicate] - javascript

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});
})
});
});

Related

nodejs mysql on pool connection Error: Connection lost: The server closed the connection

My question is similar to this post but the solution didnt work for me probably because im using a different type of mysql connection (pool). This is my code:
let config= {
host: '***',
user: 'admin',
password: '***,
port: '3306',
database: '***',
multipleStatements: true
};
const con = mysql.createPool(config);
select();
function select(){
return new Promise((resolve, reject) => {
con.getConnection(function (err, connection) {
if (err) throw err;
else
console.log("Connected!");
let sql = "SELECT * FROM bidPrice WHERE idExchangePlatform = 2;";
connection.query(sql, function (err, results, fields) {
connection.release();
connection.destroy();
if (err) throw err;
console.log(results)
resolve(results);
});
});
});
}
I also important to mention that im running this function using the following command
node --max-old-space-size=31744 index.js # Increase to 31 GB
This is because im working with millions of records from the database query
If i run this with regular node command i would be getting Javascript heap out of memory
When i tried integrating the solution i mentioned earlier to my code i just get a "killed" log after a while and then the process stops, should i handle server disconnect in a different way when using mysql.pool?
If you have big table with many rows, you will must check index for column 'idExchangePlatform' and create if doesn't make it
And simple variant your code:
function select(){
return new Promise((rs, rj) => {
let sql = "SELECT * FROM bidPrice WHERE idExchangePlatform = 2;";
pool.query(sql, (err, rows) => {
if(err)
return rj(err);
return rs(rows);
})
});
}

How to resolve error require() is not defined when calling a function from JavaScript to Node.js

I am trying to create a website and found out that Javascript does not have any way to contact a database. I did some research and found out about node.js. I created a node.js file and a small portion of my code is:
var mysql;
var con;
function initialise() {
mysql = require('mysql');
con = mysql.createConnection({
host: "name of the server the database is on",
user: "name of user that has can add and delete stuff to the database",
password: "password for the user",
database: "name of the database"
});
con.connect(function(err) {
if (err) throw err;
});
}
function getCoach(sql, con) {
return new Promise((resolve, reject) => {
con.query(sql, function (err, rows, fields) {
if (err) {
reject = (err);
throw err;
}
resolve(rows);
});
});
}
async function info() {
con.connect(function(err) {
if (err) throw err;
});
const results2 = await getCoach("SELECT username, password FROM coach", con);
return results2;
con.end();
}
I need the require('mysql') inorder to connect with the database. I tested it out and I can get a connection with the database on this file, but when I called a function in the node.js file through Javascript I got an error saying that require() is not defined. I did some research and found many things like Browserify to try and fix this issue, but nothing is working. How do I remove the error so that I can connect to the database that I created through JavaScript. What am I missing and is there a better way of doing this?
Try including your require statement outside the function like this:
const mysql = require("mysql")

MYSQL Node Issue

Running the below code throws a MYSQL err, I've checked the syntax and it seems correct but not sure why the error is being thrown.
app.post('/:roomname/create',function(request, response){
let roomID = ""+request.params.roomname+"";
console.log(roomID);
let insertRoom = "INSERT INTO chatrooms (roomname) VALUES (?)";
conn.query(insertRoom,[roomID], function(error, result) {
if (err) throw err;
console.log("1 record inserted");
});
Error:
node_modules/mysql/lib/protocol/Parser.js:80
throw err; // Rethrow non-MySQL errors
^
ReferenceError: err is not defined
Your handling error name and callback error name is not same!
you must define same error name in both callback and handling block.
Please check use this snipet. After use this snipet if any error happening, please let me know in comment.
app.post('/:roomname/create',function(request, response){
let roomID = ""+request.params.roomname+"";
console.log(roomID);
let insertRoom = "INSERT INTO chatrooms (roomname) VALUES (?)";
conn.query(insertRoom,[roomID], function(err, result) {
if (err) throw err;
console.log("1 record inserted");
});
conn.query(insertRoom,[roomID], function(error, result) {
if (err) throw err;
In the callback function you are writing "error" but in the if you are checking "err". In the callback change it to
conn.query(insertRoom,[roomID], function(err, result) {

Node-MSSQL query transactions

I am having trouble successfully completing a transaction to my database using the node MsSQL library, https://www.npmjs.com/package/mssql. Everything seems to be executing, however, I am receiving no data to my DB. Any help is greatly appreciated, thanks!
# Create connection
config =
user: ''
password: ''
server: ''
database: ''
connection = new sql.Connection(config)
# Send to table
sendData = (a, b, dsHost, dsUsername, dsSessionname, dsMode, dsRemotelocation, dsSessionactivity, dsActivityduration) ->
transaction = new sql.Transaction(connection)
transaction.begin (err) ->
if err
console.log err
else
request = new sql.Request(transaction)
request.query "INSERT INTO dbo.sessionManager SET host=?, username=?, sessionname=?, mode=?, remotelocation=?, sessionactivity=?, activityduration=?", [dsHost, dsUsername, dsSessionname, dsMode, dsRemotelocation, dsSessionactivity, dsActivityduration], (err, recordset) ->
transaction.commit (err, recordset) ->
if err
throw err
sendData() could be invoked once or a thousand times depending on the situation.
request = new sql.Request(transaction)
request.query "INSERT INTO dbo.sessionManager SET host=?, ...], (err, recordset) ->
// I think that your query is incorrect, e.g. by db constraints.
// So you need check err here.
transaction.commit (err, recordset) ->
if err
throw err

node js Insert into mysql variable not work

I am using MySql with node.js
i have this query and it works:
connection.query('insert into username (name) values ("msg")', function(err, rows, fields) {
if(!err) {
} });
it inserts the string "msg", not the value of the variable msg, but when I want to insert the variable this does not work:
connection.query('insert into username (name) values '+ msg, function(err, rows, fields) {
if(!err) {
} });
for example:
var msg = "hello world!";
You are missing the parenthesis and the quotes that make a valid insert statement in the second case. You are building a sql statement that looks like this:
'insert into username (name) values hello world'
which is malformed. Use the util module to make your string formatting easier:
var util - require('util');
var mySql = util.format('insert into username (name) values ("%s")', 'hello world');
connection.query(mySql, function(err, rows, fields) {
if(!err) {
} });
try this code
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass',
database: 'db_name'
});
connection.query(`INSERT INTO user_table (name, mail, pass) VALUES ('${user_name}', '${user_name}', '${user_name}');`, function (err, result, fields) {
if (err) throw err;
});

Categories