1. 程式人生 > >Node.js連接mysql

Node.js連接mysql

ole bob 單個 ror fun eat 代碼 mit host

================創建鏈接池=====================
var mysql = require(‘mysql‘);
var pool = mysql.createPool({
connectionLimit : 10,
host : ‘example.org‘,
user : ‘bob‘,
password : ‘secret‘,
database : ‘my_db‘
});

pool.query(‘SELECT 1 + 1 AS solution‘, function (error, results, fields) {

if (error) throw error;
console.log(‘The solution is: ‘, rows[0].solution);
});

pool.end(function (err) {
// all connections in the pool have ended
});


=================創建單個鏈接======================
var mysql = require(‘mysql‘);
var connection = mysql.createConnection({
host : ‘localhost‘,
user : ‘me‘,

password : ‘secret‘,
database : ‘my_db‘
});

connection.connect(); //這行代碼不寫,也可以通過調用查詢來隱式地建立連接:

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

connection.end();

Node.js連接mysql