node 应该是如今最火热的技术了。

看完了朴灵的《深入浅出 nodejs》,终是要练练手吧。

第一反应是操作数据库,废话不多说,直接开始。

Mysql 服务搭建

先用brew安装mysql

1
brew install mysql

安装完,尝试登录使用,启动。

1
mysql.server start

这时就可以登录使用mysql了,

1
mysql -h localhost -u root -p XXX

其中 -h 后参数是地址的意思,-u 后是用户名(默认root),-p后是密码(初始为空)

img1

可以试着查看数据库。

1
show databases

img2

可以试着查看数据库中的表。

1
2
use <databaseName>
show tables

img3

node 代码

连接数据库

1
2
3
4
5
6
7
8
9
10
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'school',
port:'3306'
});
connection.connect();

插入一个user

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var usr = {id:'2334',name:'zhangsan',address:'zhangsan',year:'2016-06-01'};
connection.query('insert into teacher set ?', usr, function(err, result) {
if (err) throw err;
console.log('inserted zhangsan');
console.log(result);
console.log('\n');
});
connection.query('select * from teacher', function(err, rows, fields) {
if (err) throw err;
console.log('selected after inserted');
for(var i= 0,usr;usr=rows[i++];){
console.log('user name='+usr.name + ', address='+usr.address);
}
console.log('\n');
});

img4

更新user,带条件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
connection.query('update teacher set address="hangzhou" where name="libin"', {address:'shanghai'}, function(err, result) {
if (err) throw err;
console.log('updated zhangsan\'s address to ddd');
console.log(result);
console.log('\n');
});
connection.query('select * from teacher', function(err, rows, fields) {
if (err) throw err;
console.log('selected after updated');
for(var i= 0,usr;usr=rows[i++];){
console.log('user name='+usr.name + ', address='+usr.address);
}
console.log('\n');
});

删除 user,带条件

1
2
3
4
5
6
connection.query('delete from teacher where name="zhangsan"', {address:'zhangsan'}, function(err, result) {
if (err) throw err;
console.log('deleted zhangsan');
console.log(result);
console.log('\n');
});

查询user,所有

1
2
3
4
5
6
7
8
9
connection.query('select * from teacher', 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 + ', address='+usr.address);
}
console.log('\n');
});

关闭连接

1
connection.end();