node连接mysql

# 下载mysql依赖

安装一下依赖包。

npm i -D mysql
npm i -D node-mysql
1
2

# 引入配置包

在根目录下的model/db.js文件中引入包。

const mysql = require('mysql');

const client = (sql, arg, callback) => {
  //1.创建连接
  let config = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'vue'
  })
  //2.开始连接
  config.connect()
  //3.对数据库进行增删查改
  config.query(sql, arg, (err, data) => {
    callback && callback(err, data)
  })
  //4.关闭数据库
  config.end()
}

module.exports = client;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 具体使用方法

这里以一个注册登录为例展示使用方法。

var express = require('express');
var router = express.Router();
var db = require('../model/db');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/user/list', function (req, res, next) {
  db('select * from user', [], (err, data) => {
    if (err) {
      res.json({
        code: 101,
        info: '获取失败',
        data: err
      })
    }
    if (data) {
      res.json({
        code: 200,
        info: '获取成功',
        data: data
      })
    }
  })
})

router.post('/user/reg', function (req, res, next) {
  console.log(req.body);
  db('select * from user where username = "' + req.body.userName + '"', [], (err, data) => {
    if (err) {
      res.json({
        code: 101,
        info: '获取失败',
        data: err
      })
    }
    if (data) {
      if (data.length !== 0) {
        res.json({
          code: 109,
          info: '用户已存在!',
          data: []
        })
      } else {
        db('insert into user(id, username, password, isAdmin) values(?, ?, ?, ?)', [req.body.userId, req.body.userName, req.body.userPwd, 1], (err, data) => {
          if (err) {
            res.json({
              code: 101,
              info: '注册失败',
              data: err
            })
          }
          if (data) {
            res.json({
              code: 200,
              info: '注册成功',
              data: data
            })
          }
        })
      }
    }
  })

})

router.post('/user/login', function (req, res, next) {
  console.log(req.body);
  db('select * from user where username = "' + req.body.userName + '"', [], (err, data) => {
    if (err) {
      res.json({
        code: 101,
        info: '获取失败',
        data: err
      })
    }
    if (data) {
      if (data.length !== 0) {
        if (data[0].username != req.body.userName) {
          res.json({
            code: 109,
            info: '用户昵称错误!',
            data: []
          })
         } else if (data[0].password != req.body.userPwd) {
          res.json({
            code: 109,
            info: '密码错误!',
            data: []
          })
        } else {
          res.json({
            code: 200,
            info: '登录成功!',
            data: []
          })
        }
      } else {
        res.json({
          code: 109,
          info: '用户不存在!',
          data: []
        })
      }
    }
  })

})

module.exports = router;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112

# 调用接口

node bin/www.js
1

这时候我们就可以调用接口了。

解决跨域问题方法

app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", '*');
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Allow-Methods","*");//允许访问的方式
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});
1
2
3
4
5
6
7

调用接口:一个注册案例。

这里使用axios

//用户信息
this.userInfo = {
  isLogin: true,
  userId: Date.parse(new Date()),
  userName: this.user.name,
  userPwd: this.user.pwd,
  token: 'auth' + Date.parse(new Date())
}
//注册
this.$axios.post(api.addUser, this.userInfo).then((res) => {
  if (res.data.code === 109) {
    this.isSucc = false
    this.isShowTip = true
    this.tipText = res.data.info
  } else {
    this.isSucc = true
    this.isShowTip = true
    this.tipText = res.data.info
    this.goHome(userInfo)
  }
}).catch((error) => {
  console.error(error)
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 方法封装

# 连接数据库

const db = require('mysql');

// 基本信息
let databaseInfo = {
  host: 'localhost',
  user: 'me',
  password: 'secret',
  database: 'my_db'
}
// 连接信息
let mysql = db.createConnection(databaseInfo);

function createConnect (cb) {
  let succRes = {
    code: 200,
    msg: 'get_succ',
    data: {
      info: '数据库连接成功!',
      des: ''
    }
  }
  let failRes = {
    code: 101,
    msg: 'get_fail',
    data: {
      info: '数据库连接失败!',
      des: ''
    }
  }
  mysql.connect((err) => {
    if (err) {
      failRes.data.des = err.stack;
      cb(failRes);
      throw new Error(err);
    }
    failRes.data.des = connection;
    cb(failRes);
  });
}

function cancelConnect () {
  mysql.end();
}

let config = {
  mysql: mysql,
  create: createConnect,
  end: cancelConnect
}

export default config;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const config = require('./config');
const mysql = config.mysql;

function selectData (cb) {
  let sql = 'show databases';
  mysql.query(sql, (err, results, fields) => {
    if (err) {
      cb(err);
    }
    cb(results);
  })
}

function insertData (table,cb) {
  let sql = `create database ${table}`;
  mysql.query(sql, (err, results, fields) => {
    if (err) {
      cb(err);
    }
    cb(results);
  })
}

function deleteData (table,cb) {
  let sql = `drop database ${table}`;
  mysql.query(sql, (err, results, fields) => {
    if (err) {
      cb(err);
    }
    cb(results);
  })
}

const db = {
  selectData,
  insertData,
  deleteData
}

export default db;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

# 创建表

const config = require('./config');
const mysql = config.mysql;

function createData (tableName, contents, cb) {
  // column_name column_type
  let sql = `CREATE TABLE ${tableName} (${contents})`;
  mysql.query(sql, (err, results, fields) => {
    if (err) {
      cb(err);
    }
    cb(results);
  })
}

function deleteData (table,cb) {
  let sql = `drop table ${table}`;
  mysql.query(sql, (err, results, fields) => {
    if (err) {
      cb(err);
    }
    cb(results);
  })
}

const table = {
  createData,
  deleteData
}

export default table;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

# 查询

const config = require('./config');
const mysql = config.mysql;

function selectData (tables, contents, conditions, cb) {
  let sql = `SELECT ${contents} from ${tables} ${conditions}`;
  mysql.query(sql, (err, results, fields) => {
    if (err) {
      cb(err);
    }
    cb(results);
  })
}

function insertData (table, content, fields,cb) {
  let sql = `INSERT INTO ${table} (${fields}) values(${content})`;
  mysql.query(sql, (err, results, fields) => {
    if (err) {
      cb(err);
    }
    cb(results);
  })
}

function updateData (table, contents, conditions,cb) {
  let sql = `UPDATE ${table} SET ${contents} ${conditions}`;
  mysql.query(sql, (err, results, fields) => {
    if (err) {
      cb(err);
    }
    cb(results);
  })
}

function deleteData (table, conditions,cb) {
  let sql = `DELETE FROM ${table} ${conditions}`;
  mysql.query(sql, (err, results, fields) => {
    if (err) {
      cb(err);
    }
    cb(results);
  })
}

const query = {
  selectData,
  insertData,
  updateData,
  deleteData,
}

export default query;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

# 最后

今天就到这里。

分享至:

  • qq
  • qq空间
  • 微博
  • 豆瓣
  • 贴吧