node.js操作mysql数据库之增删改查

原创 zhonghaisheng 随笔 前端笔记 198阅读 2018-07-30 11:16:44 举报

安装mysql模块

npm install mysql

数据库准备

mysql server所在的机器是本地localhost,登录账户就用root@123456

在mysql中创建test数据库

在test数据库中创建一张notes表

var express = require('express');
var app = express();

var mysql=require('mysql');

var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database : 'test',
port:'3306'
});

connection.connect();

//增加一条记录
var usr={id:53,name:'鲁滨逊漂流记'};
connection.query('insert into notes set ?', usr, function(err, result) {
if (err) throw err;

console.log('inserted notes');
console.log(result);
console.log('\n');

});

//修改一条记录
connection.query('update notes set name="朝花夕拾" where name="鲁滨逊漂流记"', {id:53}, function(err, result) {
if (err) throw err;

console.log('updated notes\'s name');
console.log(result);
console.log('\n');

});

//删除一条记录
connection.query('delete from notes where name="朝花夕拾"', {id:53}, function(err, result) {
if (err) throw err;

console.log("deleted '朝花夕拾'");
console.log(result);
console.log('\n');

});

//查询所有记录
connection.query('select * from notes', function(err, rows, fields) {
if (err) throw err;

console.log('selected after deleted');
for(var i= 0,usr;usr=rows[i++];){
    console.log('notes id='+usr.id + ', name='+usr.name);
}

console.log('\n');

});

connection.end();

app.get('/',function(req,res){
res.send('hello');
})

//hello接口
app.get('/hello', (req, res) => {
res.json({"status":1})
})

app.listen(3000);

console.log('server started!');

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复