安装
$ sudo npm install mysql
简单的连接
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'datasoft123',
database : 'hr'
});
connection.connect();
connection.query('SELECT * FROM employees', function(err, rows, fields)
{
if (err) throw err;
console.log(rows[0]);
});
connection.end();
//输出结果格式
{ EMPLOYEE_ID: 100,
FIRST_NAME: 'Steven',
LAST_NAME: 'King',
EMAIL: 'SKING@example.com',
PHONE_NUMBER: '515.123.4567',
HIRE_DATE: Wed Jun 17 1987 00:00:00 GMT+0530 (India Standard Time),
JOB_ID: 'AD_PRES',
SALARY: 24000,
COMMISSION_PCT: 0,
MANAGER_ID: 0,
DEPARTMENT_ID: 90 }
查询
connection.connect(function(err) {
if (err) throw err;
connection.query("SELECT * FROM customers", function (err, result) {
if (err) throw err;
console.log(result);
});
});
插入
connection.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
更新
connection.connect(function(err) {
if (err) throw err;
var sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
});
删除
connection.connect(function(err) {
if (err) throw err;
var sql = "DELETE FROM customers WHERE address = 'Mountain 21'";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("Number of records deleted: " + result.affectedRows);
});
});
感觉直接写sql很不安全。
因为不让转载就加个写个比较好的文章链接。
http://www.jianshu.com/p/47f8816bf696
参考:
http://www.w3resource.com/node.js/nodejs-mysql.php
https://www.w3schools.com/nodejs/nodejs_mysql_select.asp