我正在尝试通过节点js将数据插入MySQL用户表,我正在使用 和以下 https://github.com/felixge/node-mysql#escaping-query-values
下面是我的代码,我真的不知道出了什么问题,我无法通过postData查询插入数据,但是如果我尝试执行测试查询,它就会起作用。
为什么postData查询没有工作?
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port : 3306,
database : 'csc309',
user : 'root',
password : 'root'
});
connection.connect();
var postData = {username: 'user4',
firstname: 'first',
lastname: 'last',
password: 'password',
email: 'test2@email.com'};
/*
var test = connection.query('INSERT INTO user (username, firstname, lastname, password, email) VALUES
("user4", "first", "last", "password", "sdfsdf@hotmail.com")');
*/
var query = connection.query('INSERT INTO user VALUES ?', postData, function(err, result) {
console.log('The solution is: ', result);
});
这是我的用户sql用户表。
create table user (
id int AUTO_INCREMENT PRIMARY KEY,
username varchar(40) UNIQUE NOT NULL,
firstname varchar(40) NOT NULL,
lastname varchar(40) NOT NULL,
password varchar(100) NOT NULL,
created_at datetime NOT NULL,
email varchar(40) UNIQUE NOT NULL,
reputation int DEFAULT 0,
mailing_address varchar(100),
phone varchar(20),
gender varchar(10),
admin tinyint default 0 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
答案 0 :(得分:2)
如果要插入具有显式指定值的行,将对象传递给转义查询,则应使用INSERT ... SET
表单:
var query = connection.query('INSERT INTO user SET ?', postData, function(err, result) {
console.log('The solution is: ', result);
});
生成的查询将如下所示:
INSERT INTO user SET `username` = 'user4', `firstname` = 'first', `lastname` = 'last', `password` = 'password', `email` = 'test2@email.com'