插入mysql变量不工作

node js Insert into mysql variable not work

本文关键字:工作 变量 mysql 插入      更新时间:2023-09-26

我正在使用MySql与node.js

我有这个查询,它的工作:

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

     } });

它插入字符串"msg",而不是变量msg的值,但是当我想插入变量时,这不起作用:

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

     } });
例如:

var MSG = "hello world!";

您缺少了在第二种情况下构成有效插入语句的圆括号和引号。您正在构建一个sql语句,看起来像这样:

'insert into username (name) values hello world'

是畸形的。使用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) {

 } });

试试这个代码

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;
  });