db.js 代码:
console.log("开始连接mysql......");
var conn = require("mysql").createClient({
'host':'localhost',
'port':'3306',
'user':'root',
'password':''
});
ClientConnectionReady = function(client){
client.query('USE nodejs',function(error,results){
if(error){
console.log("数据库连接错误:" + error.message);
client.end();
return;
}
console.log("已经建立到数据库:nodejs的连接");
//插入一条测试数据
var sql = "INSERT INTO test SET id=?, user_name=?, nick_name=?",
values = [ , "jim", "jimmy"];
client.query(sql, values, function(error, results){
if(error) {
console.log("插入记录出错: " + error.message);
client.end();
return;
}
console.log('Inserted: ' + results.affectedRows + ' row.');
console.log('Id inserted: ' + results.insertId);
});
getData(client);
});
}
getData = function(client){
var sql = "select * from test";
client.query(sql, function selectCb(error, results, fields){
if(error){
console.log('查询出错:'+error.message);
client.end();
return;
}
console.log("查询表:test");
//console.log(fields);
console.log('查到结果:' + results.length + "条");
if(results.length > 0){ //查看第一条记录
var firstResult=results[0];
console.log('id:' + firstResult['id']);
console.log('user_name:' + firstResult['user_name']);
console.log('nick_name:' + firstResult['nick_name']);
}
});
client.end();
console.log("关闭数据库连接");
}
ClientConnectionReady(conn);