nodeJs链接Mysql做增删改查的简单操作
时间:2021-06-27 08:21:22|栏目:NodeJS|点击: 次
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:
栏 目:NodeJS
本文地址:http://www.codeinn.net/misctech/148787.html