作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在尝试使用 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
而不是 VALUES
。 INSERT INTO ... SET x = y
是有效的 MySQL 查询,而 INSERT INTO ... VALUES x = y
不是。
关于mysql - INSERT INTO 因 node-mysql 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21779528/
我是一名优秀的程序员,十分优秀!