INSERT INTO失败,出现node-mysql [英] INSERT INTO fails with node-mysql

查看:188
本文介绍了INSERT INTO失败,出现node-mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to insert some data with node.js. I have written the following code and installed MySQL support via npm, but I failed to INSERT INTO the table.

这是我的代码:

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>

错误消息是:

您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以在第1行附近使用正确的语法.'username'='Test','password'='test'

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

我怎么了?

推荐答案

请注意

Pay attention to the 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则不是.

Notice that they use SET instead of VALUES. INSERT INTO ... SET x = y is a valid MySQL query, while INSERT INTO ... VALUES x = y is not.

这篇关于INSERT INTO失败,出现node-mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆