var data=["玉米","1004","1000","枯梢病","保定","12123","test","测试"] let sqls = "INSERT INTO sales (product,coverage,number,diseases,address,finder,manager,remark) VALUES('"+data[0]+"','"+data[1]+"','"+data[2]+"','"+data[3]+"','"+data[4]+"','"+data[5]+"','"+data[6]+"','"+data[7]+"')" 为什么报错 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 INTO sales (product,coverage,number
The error in your SQL syntax likely arises from the way you are constructing the SQL query string in JavaScript. When building SQL statements dynamically, it's important to handle the data values properly to avoid syntax errors, especially when dealing with strings and quotes.
Here's a safer and more correct way to construct the SQL query string using template literals in JavaScript:
var data = ["玉米", "1004", "1000", "枯梢病", "保定", "12123", "test", "测试"]; let sqls = `INSERT INTO sales (product, coverage, number, diseases, address, finder, manager, remark) VALUES ('${data[0]}', '${data[1]}', '${data[2]}', '${data[3]}', '${data[4]}', '${data[5]}', '${data[6]}', '${data[7]}')`; console.log(sqls);
Using template literals (enclosed by backticks `
) allows for easier string interpolation and reduces the likelihood of syntax errors. Here is the generated SQL statement
sql
INSERT INTO sales (product, coverage, number, diseases, address, finder, manager, remark) VALUES ('玉米', '1004', '1000', '枯梢病', '保定', '12123', 'test', '测试')
Make sure your database connection and execution code are also correctly set up to run this SQL query. Additionally, it's highly recommended to use parameterized queries to prevent SQL injection and other issues:
javascript
复制代码
const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'your-hostname', user: 'your-username', password: 'your-password', database: 'your-database' }); connection.connect(); const sql = `INSERT INTO sales (product, coverage, number, diseases, address, finder, manager, remark) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`; const values = ["玉米", "1004", "1000", "枯梢病", "保定", "12123", "test", "测试"]; connection.query(sql, values, (error, results, fields) => { if (error) throw error; console.log('Inserted:', results.insertId); }); connection.end();
This approach uses parameterized queries to safely insert the data into the database, which is a best practice to avoid SQL injection attacks.
4o