如发现博文存在问题,可以随时滴滴我

Node.js数据库的配置,封装query

准备两个js文件

 其中config.js是配置数据库信息

  1. // 配置链接数据库参数
  2. module.exports = {
  3. host:'localhost',//数据库地址
  4. user:'root',//账户名
  5. password:'root',//密码
  6. port:'3306',//端口
  7. database:'webserver',//数据库名
  8. connectTimeout:5000, // 连接超时
  9. multipleStatements:false // 是否允许一个query中包含多条sql语句
  10. };

db.js是封装query函数

  1. const mysql = require('mysql')
  2. const config = require('./config') //引入数据库配置信息
  3. // 向外暴露方法
  4. module.exports = {
  5. query: function(sql, params, callback) {
  6. // 每次使用的时候需要创建链接,数据操作完成之后要关闭连接
  7. let conn = mysql.createConnection(config);
  8. conn.connect(function(err) {
  9. if(err) {
  10. console.log('数据库链接失败');
  11. throw err;
  12. }
  13. // 操作数据库
  14. // 传入三个参数,第一个参数sql语句,第二个参数sql语句中需要的数据,第三个参数回调函数
  15. conn.query(sql, params, function(err, res, fields) {
  16. if(err) {
  17. console.log('数据操作失败');
  18. throw err;
  19. }
  20. // 将查询出来的数据返回给回调函数
  21. callback && callback(res, fields);
  22. // res作为数据操作后的结果,fields作为数据库连接的一些字段
  23. // 停止链接数据库,必须再查询语句后,要不然一调用这个方法,就直接停止链接,数据操作就会失败
  24. conn.end(function(err) {
  25. if(err) {
  26. console.log('关闭数据库连接失败!');
  27. throw err;
  28. }
  29. });
  30. });
  31. });
  32. }
  33. };

准备测试

有一个test.js

  1. const express = require('express')
  2. const db = require('./db/db')
  3. const cors = require('cors')// 跨域
  4. const bodyParser = require('body-parser');//解析参数
  5. const app = express();
  6. app.use(cors()) //解决跨域
  7. app.use(bodyParser.json());
  8. app.use(bodyParser.urlencoded({extended: true}));//允许表单请求
  9. app.listen(9000,()=>console.log('服务启动'))
  10. //查询
  11. app.get('/search',async (req,res,next)=>{
  12. try{
  13. db.query('SELECT * FROM user', [], function(result, fields) {
  14. res.json({result})
  15. });
  16. }catch(error){
  17. next(error)//抛错,将错误携带致回调函数,往下传递
  18. }
  19. })

 

posted @ 2019-12-24 10:18  webxue  阅读(756)  评论(0编辑  收藏  举报