【发布时间】:2017-06-12 03:53:26
【问题描述】:
我无法使用 mysql 节点包从 Node.js 连接到我个人计算机上的本地 mysql 数据库。我的 Node.js 程序与 mysql 数据库位于同一台计算机上,因此不需要联网。我尝试了多种堆栈溢出解决方案,但似乎都没有。
我的目录结构:
project_root/
mysql/
connection.js
node_modules/
....
server.js
package.json
connection.js 的内容如下所示,错误出现在“connection.connect”那一行。我知道这是因为运行“function(err)”的回调函数在控制台中打印“Mysql 连接错误”,然后打印“null”。
var fs = require('fs');
var mysql = require('mysql');
var connection_data = JSON.parse(fs.readFileSync('../config/mysql.json', 'utf8'));
// JSON.stringify(connection_data)
// {"host":"127.0.0.1","port":3306,"user":"root","passwd":"xxxxxxxxxxx","db":"mydatabase"}
var connection = mysql.createConnection({
host : connection_data['host'],
user : connection_data['user'],
password : connection_data['passwd'],
database: connection_data['db'],
charset: "utf8_general_ci",
socketPath : '/tmp/mysql.sock'
});
export_connection = connection.connect(function(err) {
console.log("Mysql connection error");
console.log(err);
});
module.exports = export_connection
其他链接建议在下面给出的命令行中查看 mysql 状态。我什至将 Node.js mysql 连接设置为连接到状态中显示的相同套接字。
mysql> status
--------------
mysql Ver 14.14 Distrib 5.7.18, for osx10.12 (x86_64) using EditLine wrapper
Connection id: 237509
Current database:
Current user: root@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server version: 5.7.18 MySQL Community Server (GPL)
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: latin1
Db characterset: latin1
Client characterset: utf8
Conn. characterset: utf8
UNIX socket: /tmp/mysql.sock
Uptime: 1 day 8 hours 9 min 18 sec
注意connection_data['host']是127.0.0.1,connection_data['user']是root,connection_data['db']对应一个已有的数据库。
【问题讨论】:
标签: javascript mysql node.js