首先使用npm安装mysql包:
$ npm install mysql
连接数据库:
var mysql = require('mysql'); //引入mysql包
//创建数据库连接
var connection = mysql.createConnection({
host : 'localhost', //主机地址
user : 'root', //数据库用户
password : '123456', //密码
database : 'test' //数据库名
});
connection.connect();
数据库操作:
查询:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database: 'test'
});
connection.connect();
var sql = 'SELECT * FROM table_name';//查询语句
connection.query(sql,function (err, result) {
if(err){
console.log('[SELECT ERROR] - ',err.message);
return;
}
console.log(result);
});
connection.end();
插入:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database: 'test'
});
connection.connect();
var Sql = 'INSERT INTO table_name(id,name) VALUES(?,?)';//插入的sql语句
var SqlParams = ['1', '第一个']; //作为参数传入query函数,数组的值与sql语句中value对应
connection.query(addSql,addSqlParams,function (err, result) {
if(err){
console.log('[INSERT ERROR] - ',err.message);
return;
}
console.log(result);
});
connection.end();
更新:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database: 'test'
});
connection.connect();
var Sql = 'UPDATE table_name SET name = ? WHERE Id = ?';
var SqlParams = ['第二个',2];
connection.query(Sql,SqlParams,function (err, result) {
if(err){
console.log('[UPDATE ERROR] - ',err.message);
return;
}
});
connection.end();
删除:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database: 'test'
});
connection.connect();
var Sql = 'DELETE FROM table_name where id=1';
connection.query(Sql,function (err, result) {
if(err){
console.log('[DELETE ERROR] - ',err.message);
return;
}
});
connection.end();