nodeJS踩坑之路---数据库篇。

目录

连接数据库

常见问题一:怎么看数据库是否连接成功。

常见问题二:怎么对数据库返回的数据进行操作。

进行数据库操作时常见的mysql错误:

1.Nodejs中“循环+异步” :当我们在sql下用返回的数据调用foreach再进行sql查询,此时内层foreach下的sql查询存在异步问题。


连接数据库

下载mysql模块:npm install --save mysql

引用mysql模块:const mysql = require('mysql');//引入mysql连接数据库的中间件

创建链接池:db = mysql.createPool({host:'localhost',post:'3306',user:'root',password:'******',database:'数据库名'});

对数据库进行操作:

db.query(`SELECT * FROM user `,(err,data) => {

if(err){

res.status(500).send("数据库操作出错");

}else{

res.send(data)
}

})

常见问题一:怎么看数据库是否连接成功。

直接打印db,如果db中包含了自己的数据库的一些信息,则表示数据库连接成功。

常见问题二:怎么对数据库返回的数据进行操作。

对于数据库直接返回的data返回的是一个数组对象,但是没法直接取里面的值。可以通过JSON进行两次封装,就可以转化为正常数组对象啦。

let results = JSON.stringify(data);

let newdata = JSON.parse(results);

此时的newdata已经是正常的数组对象啦,可以进行常规操作了。

进行数据库操作时常见的mysql错误:

1.Nodejs中“循环+异步” :

当我们在sql下用返回的数据调用foreach再进行sql查询,此时内层foreach下的sql查询存在异步问题。

灵感解决来源:http://blog.csdn.net/fangjian1204/article/details/50585073

解决方法一:使用async组件。

引入组件:npm install --save async

使用组件:var async = require('async');

db.query(`SELECT u.u_id,u.u_name,u.u_img,u.u_company,u.u_major,c.c_id,c.c_upid,c.c_content,c.c_ftime,c.c_support

FROM comment c,user u WHERE c.c_uid = u.u_id and c_aid = '${req.body.a_id}' and c_upid = '' `, (err, rows)=> {

if (err) {

console.log(err);

res.status(500).send('插入数据库错误');

}else{

resData.returnCode = 0;

resData.returnMsg = '获取文章列表成功';

async.map(rows, (item, callback) => {

db.query( `SELECT u.u_id,u.u_name,u.u_img,u.u_company,u.u_major,c.c_id,c.c_upid,c.c_content,c.c_ftime,

c.c_support FROM comment c,user u WHERE c.c_uid = u.u_id and c_upid = '${item.c_id}' `, (err, tags) => {

let newResults = JSON.stringify(tags);

newChildData = JSON.parse(newResults);

item.childrenList = newChildData;

callback(null, item);

});

}, function(err,results) {

resData.data = results;

res.send(JSON.stringify(resData));

});

}

});

上面的resData是我为了返回后端封装的一个返回数据对象。下面是封装好的数据,返回给了前台。

2.sql语句报错:Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '','7512a5cf-c195-42a1-97d0-c0d0fb699824','1577958435000','0')' at line 2

解决:错误的意思是说,你在 7512a5cf-c195-42a1-97d0-c0d0fb699824','1577958435000','0') 这一块代码处有个错误。具体在哪儿呢,先从他说的代码地方开始

db.query(`INSERT INTO collection (coll_id,coll_uid,coll_aid,coll_status,coll_time,coll_wuid,coll_wtime,coll_invalid) VALUES

('${uuid.v4()}','${req.body.coll_uid}','${req.body.coll_aid}','0',${timeObj.getTimeStamp()}','${req.body.coll_aid}',

'${timeObj.getTimeStamp()}','0')`,(err,data) => {

结果发现在获取coll_time时,${timeObj.getTimeStamp()}外的单引号少一个,因为这段是复制过来改的,改的时候写错了。

3. sql语句报错:Error: ER_WRONG_VALUE_COUNT_ON_ROW: Column count doesn't match value count at row 1

错误的意思是你的sql语句中的字段与数据库表中的字段不匹配。

我的问题是在insert中,少插入了一条数据,造成的错误。

更新中...

发布了21 篇原创文章 · 获赞 24 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_36940740/article/details/103734510
今日推荐