NodeJS连接MySQL数据库并进行操作

本文详细介绍了如何在Node.js环境中安装和配置MySQL,包括创建数据库连接、执行查询、删除和修改操作。同时,展示了如何封装数据库工具模块以提高代码复用性,并提供了添加新记录的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、安装mysql npm install mysql --save

2、使用

// <1>mysql的配置  

const mysqlConfig = {  

host:'127.0.0.1',  

port:'3306',  

user:'root',  

password:'mysql',  

database:'doubandb'  

}  

// <2>引用mysql  

const mysql = require('mysql');  

// <3> 进行连接  

const connection = mysql.createConnection(mysqlConfig);  

// <4>操作数据库  

connection.query("select * from books", (err, result) => {

      console.log(err);      

if (!err) {          

data = result;          

res.json({ data });      

            }  

});

 3、进行mysql工具的封装

<1> 定义配置信息,在config-->dbconfig.js添加mysql的配置信息

const MYSQL_CONFIG = {  

host: '127.0.0.1',  

port: '3306',  

user: 'root',  

password: 'mysql',  

database: 'doubandb'

}

 <2>封装mysqlutils.js工具

 // 引用

mysqlconst mysql = require('mysql');

const { MYSQL_CONFIG } = require('../../config/dbconfig');

// 创建连接池

const pool = mysql.createPool(MYSQL_CONFIG);

// 执行sql的方法

const exec = sql => {    return new Promise((resolve, reject) => {        

// 获取连接    

pool.getConnection((err, connection) => {

if (err) {      

// 有错误                

reject(err);          

} else {                

connection.query(sql, (err, result) => {                    

if (!err) {                        

resolve(result);                  

} else {                        

reject(err);                  

}              

});          

}            

// 当连接不再使用时,用connection对象的release方法将其归还到连接池中            connection.release();      

});  

});

}

module.exports= {    

exec

};

 <3>在使用的地方进行调用exec,传递sql

const { exec } = require('../utils/dbutils/mysqlutils');  

exec("select * from books").then(data=>{      

res.json({data});  

});

 查询

bookRouter.get('/searchList', async (req, res, next) => {  

let sql = ` SELECT b.*,a.authorname,a.authordesc  

FROM books b, author a, author_books ab  

WHERE ab.aid = a.aid AND ab.bid = b.bid `;  

// 获取查询的参数  

const { bookname, isbn, authorname } = req.query;  

if (bookname && bookname.trim() !== '') {      

sql += ` and b.bookname like '%${bookname}%' `;  

}  

if (isbn && isbn.trim() !== '') {      

sql += ` and b.isbn = '${isbn}' `;  

}  

if (authorname && authorname.trim() !== '') {      

sql += ` and a.authorname like '%${authorname}%' `;  

}  

console.log('sql:', sql);  

exec(sql).then(data => {      

res.send(JSON.stringify({ code: 0, data }));  

});

});

 删除

bookRouter.post('/del', (req, res, next) => {  

const { bids } = req.body;// bids是数组  

if (bids && bids.length > 0) {      

const paramsStr = bids.map(bid=>`'${bid}'`);      

const params = paramsStr.join(',');      

const sql = `delete from books b where b.bid in (${params}) `;      

exec(sql).then(data => {          

res.send(JSON.stringify({ code: 0, data }));      

});  

} else {      

res.json({          

code: 0,          

message: '必须要进行选择'      

});  

}});

 修改

bookRouter.post('/modify', (req, res, next) => {  

const { bookid, bookname,isbn,publishinghouse } = req.body;  

let sql =` UPDATE books b SET b.bid = b.bid `;  

if(bookname && bookname.trim()!==''){      

sql+=` , b.bookname= '${bookname}' `  

}  

if(isbn && isbn.trim()!==''){      

sql+=`, b.isbn='${isbn}' `;

}  

if(publishinghouse && publishinghouse.trim()!==''){      

sql+=` , b.publishinghouse='${publishinghouse}' `;  

}  

sql += ` WHERE b.bid = '${bookid}' `;  

exec(sql).then(data => {      

res.send(JSON.stringify({ code: 0, data }));  

});

});

 新增方法:

bookRouter.post('/add', async (req, res, next) => {  

// 向数据库中添加数据  

let { bookname, price = 10.0, isbn='',      

dateofpublication=null, publishinghouse = '',      

producer = '', originaltitle = '', translator = '',      

numberofpages = 0, contentintroduction = '', cid = null  

} = req.body;  

if(dateofpublication!==null){      

dateofpublication = `DATE_FORMAT('${dateofpublication}','%Y-%m-%d')`;  

}  

const bid = moment().get() + '_' + (Math.random() * 100000000 + 1) + '';  

const sql = `insert into books(bid,bookname, price, isbn,dateofpublication, publishinghouse ,producer, originaltitle, translator,       numberofpages, contentintroduction, cid) values('${bid}','${bookname}',${price},       '${isbn}',${dateofpublication},'${publishinghouse}','${producer}','${originaltitle}',       '${translator}',${numberofpages},'${contentintroduction}',${cid}) `;      

exec(sql).then(data => {          

res.send(JSON.stringify({ code: 0, data }));      

});

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

放揊会鼓包

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值