node如何封装mysql处理语句

数据库   发布日期:2023年06月15日   浏览次数:517

本篇内容介绍了“node如何封装mysql处理语句”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

一.所需包

  1. npm i mysql -S
  2. npm i express -S

二.MySql连接文件

  1. const mysql = require('mysql')function createConnection() {
  2. const connection = mysql.createConnection({
  3. host: '', //地址
  4. user: '', //用户名
  5. password: '', //密码
  6. port: '', //端口
  7. database: '' //数据库名
  8. });
  9. return connection;}module.exports.createConnection = createConnection;

三.封装文件

引入MySQL连接相关文件,进行连接数据库操作

  1. const mysql = require('../mysql/mysql')let connection = null;connection = mysql.createConnection();/**
  2. * 错误消息
  3. */let bad_msg = {
  4. code: 500,
  5. msg: '内部错误!'}/**
  6. * 成功消息
  7. */let success_msg = {
  8. code: 200,
  9. msg: '操作成功'}const connections = {
  10. /**
  11. * 查询方法
  12. * @param {*} table 表名
  13. * @param {*} condition 条件
  14. * @param {*} params 参数
  15. * @param {*} search 查询条件
  16. * @returns
  17. */
  18. find(table, condition, params, search = '*') {
  19. return new Promise((resolve, reject) => {
  20. let sql = `SELECT ${search} FROM ${table} WHERE ${condition}`
  21. connection.query(sql, params, (err, result) => {
  22. if (err) {
  23. reject(bad_msg)
  24. } else {
  25. let _ = JSON.parse(JSON.stringify(success_msg))
  26. _.data = result resolve(_)
  27. }
  28. })
  29. })
  30. },
  31. /**
  32. * 插入方法
  33. * @param {*} table 表名
  34. * @param {*} condition 条件
  35. * @param {*} params 参数
  36. * @returns
  37. */
  38. insert(table, condition, params) {
  39. return new Promise((resolve, reject) => {
  40. const str = "?"
  41. let _ = str.repeat((condition.split(',')).length)
  42. let val = (Array.from(_)).toString()
  43. let sql = `INSERT INTO ${table}(${condition}) VALUES(${val})`
  44. connection.query(sql, params, (err, result) => {
  45. if (err) {
  46. reject(bad_msg)
  47. } else {
  48. resolve(success_msg)
  49. }
  50. })
  51. })
  52. },
  53. /**
  54. * 更新方法
  55. * @param {*} table 表名
  56. * @param {*} val 值
  57. * @param {*} condition 条件
  58. * @param {*} params 参数
  59. * @returns
  60. */
  61. update(table, val, condition, params) {
  62. return new Promise((resolve, reject) => {
  63. let sql = `UPDATE ${table} SET ${val} WHERE ${condition}`
  64. connection.query(sql, params, (err, result) => {
  65. if (err) {
  66. reject(bad_msg)
  67. } else {
  68. resolve(success_msg)
  69. }
  70. })
  71. })
  72. },
  73. /**
  74. * 删除方法
  75. * @param {*} table 表名
  76. * @param {*} condition 条件
  77. * @param {*} params 参数
  78. * @returns
  79. */
  80. del(table, condition, params) {
  81. return new Promise((resolve, reject) => {
  82. let sql = `DELETE FROM ${table} WHERE ${condition}`
  83. connection.query(sql, params, (err, result) => {
  84. if (err) {
  85. reject(bad_msg)
  86. } else {
  87. resolve(success_msg)
  88. }
  89. })
  90. })
  91. },}module.exports = connections

四.使用

我们使用登录注册来进行演示:

  1. const express = require('express')const router = express.Router()const connections = require('../../static/connection')// token生成插件模块const jwt = require('jsonwebtoken');// Token签名var secret = ''const CreatId = require('../../static/ranId')router.post('/user/details', (req, res) => {
  2. connections.find('user_table', `ID=?`,req.user.ID).then(resp => {
  3. res.send(resp)
  4. })})router.post('/api/login', (req, res) => {
  5. connections.find('user_table', 'user=?', req.body.user).then(resp => {
  6. let {data} = resp if (data.length !== 0) {
  7. for (let i = 0; i < data.length; i++) {
  8. // 邮箱或者密码不正确的时候
  9. if (req.body.user !== data[i].user || req.body.pwd !== data[i].pwd) {
  10. res.send({
  11. code: 202,
  12. msg: '用户名或密码有误!'
  13. })
  14. } else {
  15. // 邮箱和密码输入正确
  16. if (req.body.user === data[i].user && req.body.pwd === data[i].pwd) {
  17. // 传输的token内容
  18. let token = jwt.sign({ ID: data[i].ID }, secret, { expiresIn: '72H' });
  19. // 返回结果
  20. res.send({
  21. code: 200,
  22. msg: '操作成功!',
  23. token: 'Bearer ' + token,
  24. })
  25. }
  26. }
  27. }
  28. } else {
  29. res.send({
  30. code: 400,
  31. msg: '账号不存在请注册!'
  32. })
  33. }
  34. }).catch(e => {
  35. res.send(e)
  36. })})router.post('/api/register', (req, res) => {
  37. connections.find('user_table', 'user=?', req.body.user).then(resp => {
  38. if (resp.data.length > 0) {
  39. res.send({
  40. code: 202,
  41. msg: '该用户已经存在!'
  42. })
  43. } else {
  44. let _ = req.body let id = CreatId(3) + CreatId(3)
  45. connections.insert('user_table', 'ID,user,pwd,avatarUrl,location,RegisterTime,isAdmin,isDel', [id, _.user, _.pwd, '/static/userimg/user.webp', _.location, Date.now(), 0, 0]).then(resps => {
  46. // 传输的token内容
  47. let token = jwt.sign({ ID: id }, secret, { expiresIn: '72H' });
  48. // 返回结果
  49. res.send({
  50. code: 200,
  51. msg: '操作成功!',
  52. token: 'Bearer ' + token,
  53. })
  54. })
  55. }
  56. })})module.exports = router

以上就是node如何封装mysql处理语句的详细内容,更多关于node如何封装mysql处理语句的资料请关注九品源码其它相关文章!