nodejs连接MysqL
,首先安装了MysqL之后,在cmd界面安装nodeJs的MysqL模块:npm install MysqL
MysqL中创建数据库“nodetry1”,再创建表table2:
指定id为主键:
//选择数据库和表
var TEST_DATABASE = 'nodetry1';
var TEST_TABLE = 'table2';
var TEST_DATABASE = 'nodetry1';
var TEST_TABLE = 'table2';
var connection = mysql.createConnection({
host: 'localhost',user: 'root',password: '123456'
});
//连接数据库
connection.connect();
//选择查询的数据库
connection.query("use " + TEST_DATABASE);
// 增加
connection.query('insert into '+ TEST_TABLE +' (id,name,age) values (12,"二次添加会报错",77)');
// 删除
connection.query('delete from '+ TEST_TABLE +' where name = "sony"');
// 修改
connection.query('update '+ TEST_TABLE +' set name = "jiying.bao" where id = 5');
//查询
connection.query('SELECT * from '+ TEST_TABLE,function(err,rows) {
if(err) throw err;
console.log("SELECT ==> ");
for(var i in rows) {
console.log(rows[i]);
}
});
运行js: