mysql - 为什么mysql会抛出语法错误

标签 mysql node.js express syntax

这是我的 html 文件

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Node delivered HTML </title>

</head>
<body>
   <div>
    <h1>Send JSON to Node</h1>
        <button onClick="sendJSON()">Send</button>
        <p id ="result"></p>

   </div>
<script>
 var myData = [
    {
        "author": "Bill",
        "title": "Chris",
        "genre": "Chrisdss",
        "price": 20
    },
    {
        "author": "Bill",
        "title": "Chrisss",
        "genre": "Chrdsdss",
        "price": 24
    }
    ]

function sendJSON(){

console.log(myData);
var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       document.getElementById("result").innerHTML =
       this.responseText;
    }
 };
xmlhttp.open("POST", "http://localhost:3000");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify(myData));

}

</script>
</body>
</html>

这是我的 server.js 文件

const express = require('express')
const bodyParser = require('body-parser')
const mysql = require('mysql');
const path = require('path')
const app = express()

var TABLE = 'table';
var books =[]
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "0december"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");

});



app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname+ '/frontend.html'));
});

app.post('/', function(req, res) {

var jsondata = req.body;
var values = [];
console.log(req.body);
for(var i=0; i< jsondata.length; i++){
  values.push([jsondata[i].author,jsondata[i].title,,jsondata[i].genre,,jsondata[i].price]);
}

//Bulk insert using nested array [ [a,b],[c,d] ] will be flattened to (a,b),(c,d)
con.query('INSERT INTO table (author,title,genre,price) VALUES ?', [values], function(err,result) {
  if(err) {
     res.send('Error');
     console.log(err);
  }
 else {
     res.send('Success');
  }
});
});


app.listen(3000, () => console.log('Books API listening on port 3000'))

我的服务器运行完美,但我尝试了很多方法,但出现 SQL 语法错误。我也尝试了 W3C 教程,但仍然遇到同样的错误。也许是因为我的数据库修改不正确?

我的模型名为table,它包含id,作者,标题,流派,价格id是自动递增的,除了价格是 float 类型之外,所有内容都是字符串。尽管我的语法与教程完全相同,为什么我会收到语法错误?

编辑:错误是 sqlMessage: '您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在\'table (author,title,genre,price) VALUES (\'Bill\',\'Chris\', NULL,\'Chrisdss\' 附近使用的正确语法, NULL\' 在第 1 行', sqlState: '42000', 索引:0, sql: 'INSERT INTO 表 (作者、标题、流派、价格) VALUES (\'Bill\',\'Chris\', NULL,\'Chrisdss\', NULL, 20), (\'Bill\',\'Chrisss\',NULL,\'Chrdsdss\',NULL,24.1)' }

最佳答案

可能的解决方案

要使查询 con.query('INSERT ... ?', [values], ... 正常工作,values 应包含长度为 4 的数组,其中包含作者、标题、类型、价格。

但是,values 包含长度为 6 的数组。

您应该通过替换来从值内的数组中删除空值

values.push([jsondata[i].author,jsondata[i].title,,jsondata[i].genre,,jsondata[i].price]);

values.push([jsondata[i].author,jsondata[i].title,jsondata[i].genre,jsondata[i].price]);

现在值包含长度为 4 的数组,批量插入应该可以工作。

替代解决方案

如果需要空值,您应该指定它们的插入位置。

改变

'INSERT INTO table (author,title,genre,price) VALUES ?'

'INSERT INTO table (author,title,null_field_1,genre,null_field_2,price) VALUES ?'

其中 null_field_i 是您想要用 null 填充的字段。

关于mysql - 为什么mysql会抛出语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50436892/

相关文章:

php - MySQL根据表B行中的值将表B合并到表A中

node.js - npm 安装 grpc 失败

javascript - 如何在 electron webview 中连接到代理?

javascript - 在 node.js 中按类型和 ID 查找 XML 元素

node.js - Express.js - req.query 与 req.params

mysql - MySQL连接查询问题

mysql - 如何获取按特定列排序后除前5条记录外的所有记录

php - 我可以在 1 个 php 文件中包含多个 SQL SELECT 查询吗?

node.js - Nodejs如何将完整的错误对象发送到前端

javascript - expressjs node.js 为 google/etc 机器人和人类流量提供不同的数据