nodejs连接MySQL,首先安装了mysql之后,在cmd界面安装nodeJs的mysql模块: npm install mysql
mysql中创建数据库“nodetry1”,再创建表table2: 指定id为主键:
var mysql = require('mysql');//选择数据库和表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]); }});//关闭数据库连接connection.end();运行js:
新闻热点
疑难解答