Node.js 學(xué)習(xí)(二)——Node.js 連接 MySQL 數(shù)據(jù)庫
Node.js學(xué)習(xí)(二)——Node.js連接mysql數(shù)據(jù)庫
添加mysql模組
修改package.json
package.json添加mysql
"mysql":"latest",
更新模組
在項(xiàng)目目錄下執(zhí)行
npm install mysql
配置屬性
本地mysql準(zhǔn)備
- 先在本地mysql中創(chuàng)建了nodejsdb數(shù)據(jù)庫
- 添加t_user表
- 插入一條數(shù)據(jù)
創(chuàng)建測試js
新建一個文件connection.js,內(nèi)容如下
//連接數(shù)據(jù)庫
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',//主機(jī)地址
user: 'root',//登錄名
password: '',//密碼,我這里是空
database:'nodejsdb'//數(shù)據(jù)庫
});
connection.connect();
//查詢
connection.query('SELECT * FROM `t_user`', function(err, rows, fields) {
if (err) throw err;
console.log('結(jié)果為: ', rows);
});
//關(guān)閉連接
connection.end();
結(jié)果
執(zhí)行命令
node connection.js
參考
評論
圖片
表情
