1.環境准備
手動添加數據庫依賴:
在package.json的dependencies中新增, “mysql” : “latest”,
{ "name": "news", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "~1.13.2", "cookie-parser": "~1.3.5", "debug": "~2.2.0", "express": "~4.13.1", "jade": "~1.11.0", "morgan": "~1.6.1", "serve-favicon": "~2.3.0", "mysql":"latest" } }
使用命令安裝mysql並添加依賴:
npm install mysql -save
2.官方例子:
復制代碼 //連接數據庫 var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'open00', database:'test' }); connection.connect(); //查詢 connection.query('select * from `mytable`', function(err, rows, fields) { if (err) throw err; console.log('查詢結果為: ', rows); }); //關閉連接 connection.end();
運行node