简体   繁体   English

节点js插入mysql变量不起作用

[英]node js Insert into mysql variable not work

I am using MySql with node.js 我正在将MySql与node.js一起使用

i have this query and it works: 我有这个查询,它的工作原理:

 connection.query('insert into username (name) values ("msg")', function(err,    rows, fields) {

    if(!err) {


     } });

it inserts the string "msg" , not the value of the variable msg , but when I want to insert the variable this does not work: 它插入字符串"msg" ,而不是变量msg的值,但是当我要插入变量时,这不起作用:

connection.query('insert into username (name) values '+ msg, function(err,    rows, fields) {

    if(!err) {


     } });

for example: 例如:

var msg = "hello world!"; var msg =“世界你好!”;

You are missing the parenthesis and the quotes that make a valid insert statement in the second case. 在第二种情况下,您将缺少括号和引起有效插入语句的引号。 You are building a sql statement that looks like this: 您正在构建一个如下所示的sql语句:

'insert into username (name) values hello world'

which is malformed. 格式不正确。 Use the util module to make your string formatting easier: 使用util模块可简化字符串格式设置:

var util - require('util');
var mySql = util.format('insert into username (name) values ("%s")', 'hello world');
connection.query(mySql, function(err,    rows, fields) {

if(!err) {


 } });

try this code 试试这个代码

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'pass',
  database: 'db_name'
});

connection.query(`INSERT INTO user_table (name, mail, pass) VALUES ('${user_name}', '${user_name}', '${user_name}');`, function (err, result, fields) {
  if (err) throw err;
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM