vlambda博客
学习文章列表

Mysql 增删改查的(二)

连接nodejs的简单增删改查案例

var express = require('express');var app = express();
//1.引入所安装的mysql模块var mysql = require('mysql');
//2.链接数据库参数配置var connection = mysql.createConnection({ host:"127.0.0.1", port:3306, user:"root", password:"123456", database:"test"});//3.链接mysqlconnection.connect(function(err){ //判断是否链接成功 if(err){ throw err; } console.log('链接mysql成功');});
app.get('/index',function(req,res){ //查询操作 var sql = "select * from users" connection.query(sql,function(err,rows,field){ //参数rows:返回的是一个数组[{},{},{}],其中每个元素都是一个json对象 if(err){ throw err; } console.log(rows.length); console.log(rows[2].phone); }); res.send('查询');})

app.get('/add',function(req,res){ //入库操作 var sql = "insert into users(username,age,phone) values(?,?,?)"; var bind = ['切格瓦拉','34','110']; connection.query(sql,bind,function(err,result){ if(err){ throw err; } console.log(result); //返回是一个对象 //result.affectedRows:获取到受影响的行数 //result.insertId:获取到入库成功的自增主键的值 res.send('入库'); })})

app.get('/upd',function(req,res){ //编辑操作 var sql = "update users set username = ? , age = ?,phone = ? where uid = ? "; var bind = ['哇啦切割',44,119,7]; connection.query(sql,bind,function(err,result){ if(err){ throw err; } console.log(result); //result.affectedRows:获取到受影响的行数 }) res.send('编辑');
})
app.get('/del',function(req,res){ //删除操作 var sql = "delete from users where uid = ?"; var bind = [5]; connection.query(sql,bind,function(err,result){ if(err){ throw err; } console.log(result); //result.affectedRows:获取到受影响的行数 }); res.send('删除');})
app.listen(3000,function(){ console.log('请访问');});