nodejs连接mysql
时间:2021-07-01 10:21:17
帮助过:27人阅读
mysql = require(
‘mysql‘);
var TEST_DATABASE =
‘test‘;
var TEST_TABLE =
‘user_test‘;
//创建连接
var client =
mysql.createConnection({
host:‘127.0.0.1‘,
port:‘3306‘,
user:‘root‘,
password:‘root‘,
});
client.connect();
client.query("use " +
TEST_DATABASE);
client.query(
‘SELECT * FROM ‘+
TEST_TABLE,
function selectCb(err, results, fields) {
if (err) {
throw err;
}
if(results)
{
for(
var i =
0; i < results.length; i++
)
{
console.log("%d\t%s\t%s", results[i].sid, results[i].userName, results[i].userPwd);
}
}
client.end();
}
);
运行结果:
完成node.js连接mysql并显示结果
附:
sql脚本:
CREATE TABLE `user_test` (
`sid` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(50) DEFAULT NULL,
`userPwd` varchar(50) DEFAULT NULL,
PRIMARY KEY (`sid`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `user_test` VALUES (‘1‘, ‘李四‘, ‘sili‘);
INSERT INTO `user_test` VALUES (‘2‘, ‘张三‘, ‘123‘);
参考:https://www.npmjs.com/package/mysql
nodejs连接mysql
标签:roo 代码 png int row 目录 arch pass efault