I'm using nodejs 10.26
+ express 3.5
+ node-mysql 2.1.1
+
MySQL-Server Version: 5.6.16
.
我使用的是NodeJS 10.26+Express 3.5+NODE-MySQL 2.1.1+MySQL-Server版本: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.
我收到了4个删除请求,但只想要1个数据库请求,所以我用“;”连接了删除命令...但它总是失败。
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...
但如果我将此SQL粘贴到PhpMyAdmin中,它总是成功的……
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!
谢谢你的帮助!
更多回答
That is because you can only have 1 query per request.
这是因为每个请求只能有一个查询。
I guess you are using node-mysql. (but should also work for node-mysql2)
我猜您正在使用NODE-MySQL。(但也应该适用于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.
因此,如果您已经启用了MultipleStatement,那么您的第一个代码应该可以工作。
Using "multiplestatements: true" like shown below worked for me
使用如下所示的“Multistatements:True”对我很有效
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
要从DB(SQL)获取数据,可以使用以下函数
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
Router.get(‘/’,Function MessageFunction(req,res){//res.end(‘Hi Dear Rasikh,欢迎使用测试页。’)//=>One Way DBConn.Query(‘SELECT COUNT(NAME)AS COUNT,NAME,LAST_NAME,Phone,Email from Students’,Function(ERR,ROWS,FIELS)){//如果(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});
})
});
});
});});
This worked for me in Next.js...
这对我在Next.js中很管用。
export default async function handler(req, res) {
try {
// Build your multiple MySQL queries here
const querySql = "DELETE FROM favorites WHERE user = ? AND listingID= ?";
const querySql2 = "UPDATE properties SET saves = ? WHERE listingid = ?";
// Pass any params here
const valuesParams = [user, listingID];
const valuesParams2 = [upDateSaves, listingID];
//Execute your multiple MySQL queries here
const data = await query({query: querySql, values: valuesParams });
const data2 = await query({query: querySql2, values: valuesParams2 });
//Combine the results
const combinedResults = [data, data2];
res.status(200).json({
text: combinedResults,
});
} catch (error) {
res.status(500).json({ error: 'Error fetching data' });
}
}
更多回答
Will this work with place holder queries like connection.query('SELECT * FROM
books` WHERE author
= ?', ['David'], function (error, results, fields) { });`
这是否适用于占位符查询,如Connection.Query(‘SELECT*FORM BOOKS`WHERE Author=?’,[‘David’],Function(Error,Results,field){});`
If you want it to run parallel, you should consider using Promise.all() and use single queries for each statement instead of multiple in one statement.
如果希望它并行运行,则应考虑使用Promise.all(),并对每条语句使用单个查询,而不是在一条语句中使用多个查询。
wow, thanks for this. i can't believe the error is so misleading
哇,谢谢你这么做。我不敢相信这个错误如此具有误导性
@RossHarding you can ask it as a separate question. but yes, you can do that.
@RossHarding你可以把它作为一个单独的问题来问。但是的,你可以做到这一点。
我是一名优秀的程序员,十分优秀!