gpt4 book ai didi

mysql - INSERT INTO 因 node-mysql 而失败

转载 作者:IT老高 更新时间:2023-10-28 22:08:54 24 4
gpt4 key购买 nike

我正在尝试使用 node.js 插入一些数据。我已经编写了以下代码并通过 npm 安装了 MySQL 支持,但我未能 INSERT INTO 表。

这是我的代码:

var mysql = require('mysql');

function BD() {
var connection = mysql.createConnection({
user: 'root',
password: '',
host: 'localhost',
port: 3306,
database: 'nodejs'
});
return connection;
}

app.post("/user/create", function(req, res) {
var objBD = BD();

var post = {
username: req.body.username,
password: req.body.password
};

objBD.query('INSERT INTO users VALUES ?', post, function(error) {
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});
});

HTML 代码:

<form action="/user/create" method="POST" class="form-horizontal">
<input type="text" id="username_input" name="username">
<input type="text" id="password_input" name="password">
<input type="submit" name="Submit" value="Insert" class="btn">
</form>

错误信息是:

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 .'username' = 'Test' , 'password' = 'test' at line 1

我的错误是什么?

最佳答案

关注documentation of node-mysql :

If you paid attention, you may have noticed that this escaping allows you to do neat things like this:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
// Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'

请注意,他们使用 SET 而不是 VALUESINSERT INTO ... SET x = y 是有效的 MySQL 查询,而 INSERT INTO ... VALUES x = y 不是。

关于mysql - INSERT INTO 因 node-mysql 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21779528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com