把mysql module装到nodejs中
js代码
复制代码 代码如下:
$npm install mysql
js脚本 mysqltest.js
js代码
复制代码 代码如下:
// mysqltest.js
//加载mysql module
var client = require('mysql').client,
client = new client(),
//要创建的数据库名
test_database = 'nodejs_mysql_test',
//要创建的表名
test_table = 'test';
//用户名
client.user = 'root';
//密码
client.password = 'root';
//创建连接
client.connect();
client.query('create database '+test_database, function(err) {
if (err && err.number != client.error_db_create_exists) {
throw err;
}
});
// if no callback is provided, any errors will be emitted as `'error'`
// events by the client
client.query('use '+test_database);
client.query(
'create table '+test_table+
'(id int(11) auto_increment, '+
'title varchar(255), '+
'text text, '+
'created datetime, '+
'primary key (id))'
);
client.query(
'insert into '+test_table+' '+
'set title = ?, text = ?, created = ?',
['super cool', 'this is a nice text', '2010-08-16 10:00:23']
);
var query = client.query(
'insert into '+test_table+' '+
'set title = ?, text = ?, created = ?',
['another entry', 'because 2 entries make a better test', '2010-08-16 12:42:15']
);
client.query(
'select * from '+test_table,
function selectcb(err, results, fields) {
if (err) {
throw err;
}
console.log(results);
console.log(fields);
client.end();
}
);
执行脚本
js代码
复制代码 代码如下:
root@sammor-desktop:/var/iapps/nodejs/work# node mysqltest.js