安装 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!');
来源: http://www.qdfuns.com/article/12029/9a7bd363f798baf2a2d7fcb4f99d8320.html