Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

Here is my code:

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 code:

<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>

The error message is:

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

What is my mistake?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
587 views
Welcome To Ask or Share your Answers For Others

1 Answer

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'

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...