Node.js+MySQL示例

1 安装Node的MySQL模块,方法有两种:
 一种是手动在package.json中添加依赖(dependencies),然后执行 npm install。
一种是直接执行 npm install mysql。
package.json示例:
[javascript]
{
"name": "test",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"mysql":"latest"
}
}
[/javascript]

2 Node连接MySQL的示例:
[javascript]
let mysql = require('mysql');
let connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'850804',
database:'test'
});

connection.connect();

connection.query('SELECT 1+1 AS solution', function(err,rows,fields){
if(err) throw err;
console.log('The solution is: ', rows[0].solution);
});

connection.end();
[/javascript]

您的赞助将会支持作者创作及本站运维

发表评论


TOP