$ npm install mysql
const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '密码', database: '数据名' });
var sql = 'select * from users where id=?'; var params = [1]; connection.query(sql, params, (err, result) => { if(err) throw err; success(result) });
node.js
默认操作MySQL
都是异步
操作, 为了方便对返回值的一系列操作:, 可以使用以下实例(同步读取数据)
:
mysql.js
const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '密码', database: '数据库名' }); connection.connect(function(err, conn){ if (err) { console.log(err) } }); async function query(sql, params) { return new Promise((success, error) => { connection.query(sql, params, (err, result) => { if(err) throw err; success(result) }); }) }; module.exports = { query };
main.js
const mysql = require('./mysql') async function main() { var value = await mysql.query( 'select * from users where id=?', [1] ); console.log(value); }; main()