nodeJs数据库基本操作

本例以mysql数据库为例,在数据库操作之前需要通过npm安装mysql

1
$ npm install mysql

连接数据库

1
2
3
4
5
6
7
8
9
10
11
var mysql=require('mysql');

var connection = mysql.createConnection({
host : '主机地址',
user : '用户名',
password : '密码',
database : '数据库名',
port:'端口号'
});

connection.connect();

插入数据

1
2
3
4
5
6
7
var usr={name:'uname',password:'pword',mail:'jiangbai333@gmail.com'};
connection.query('insert into table set ?', usr, function(err, result) {
if (err) {throw er;}

console.log(result);
console.log('\n');
});

带条件更新数据

1
2
3
4
5
6
connection.query('update table set password="ddd" where name="uname"', {password:'ppp'}, function(err, result) {
if (err) {throw err;}

console.log(result);
console.log('\n');
});

带条件删除数据

1
2
3
4
5
6
connection.query('delete from table where name="uname"', {password:'ppp'}, function(err, result) {
if (err) {throw err;}

console.log(result);
console.log('\n');
});

查询数据

1
2
3
4
5
6
7
8
9
10
11
connection.query('select * from table', function(err, rows, fields) {
if (err) {throw err;}

console.log('selected after deleted');
for(var i= 0,usr;usr=rows[i++];){
console.log('user name='+usr.name + ', password='+usr.password);
}

console.log('\n');

});
谢谢你的支持