如何将mysql连接到Node JS?

时间:2019-02-05 07:56:14

标签: mysql node.js

我已经在计算机上安装了mysql,尽管它显示某些软件包可能未安装(在安装过程中),但是在尝试使用Node JS时却显示了意外的错误。

我尝试使用'npm'安装mysql的全局和本地方法,并在每个目录中尝试过,但是我的代码仍无法正常工作。

var mysql = require('mysql');

var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
  });

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
 var sql = "INSERT INTO customers (name, address) VALUES ?";
 var values = [
['John', 'Highway 71'],
['Peter', 'Lowstreet 4'],
['Amy', 'Apple st 652'],
['Hannah', 'Mountain 21'],
['Michael', 'Valley 345'],
['Sandy', 'Ocean blvd 2'],
['Betty', 'Green Grass 1'],
['Richard', 'Sky st 331'],
['Susan', 'One way 98'],
['Vicky', 'Yellow Garden 2'],
['Ben', 'Park Lane 38'],
['William', 'Central st 954'],
['Chuck', 'Main Road 989'],
['Viola', 'Sideway 1633']
  ];
con.query(sql, [values], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
 });
 });

我已经正确安装了从Node到Mysql的所有内容,并且在try catch块中显示错误。请提出一些建议

1 个答案:

答案 0 :(得分:0)

mysql和node js的连接和配置

reference url: Access MySQL server in private ec2 instance in nodejs