我正在用koa2学习nodejs,现在我想在mysql数据库中查询read & write & delete & update
个信息,我创建了一个名为dbconfig.js
的文件来配置数据库信息,另一个名为mysql.js
的文件正如书中所说的那样
const mysql = require('mysql')
const config = require('./dbconfig')
var pool = mysql.createPool({
host : config.database.HOST,
user : config.database.USERNAME,
password : config.database.PASSWORD,
database : config.database.DATABASE,
port : config.database.PORT
});
let query = function( sql, values ) {
return new Promise(( resolve, reject ) => {
pool.getConnection(function(err, connection) {
if (err) {
resolve( err )
} else {
connection.query(sql, values, ( err, rows) => {
if ( err ) {
reject( err )
} else {
resolve( rows )
}
connection.release()
})
}
})
})
}
let findAUser = function () {
let _sql = `
SELECT * FROM user where id =
`
return query(_sql)
}
let deleteAUser = function () {
let _sql = `
DELETE FROM user where id =
`
return query(_sql)
}
let updateAUser = function () {
let _sql = `
UPDATE user set name = where id =
`
return query(_sql)
}
let addAUser = function () {
let _sql = `
insert into user () value ()
`
return query(_sql)
}
module.exports={
findAUser,
deleteAUser,
updateAUser,
addAUser
}
在app.js
中,我称之为const userModel = require('./mysql');userModel.findAUser()
。
但我不知道写findAUser
,deleteAUser
,updateAUser
,addAUser
,你能帮助我吗?非常感谢。
答案 0 :(得分:0)
答案 1 :(得分:0)
这里有两件事:
query
函数中,我会将connection.release()
置于拒绝/解析之上。否则它可能不会被调用。findAUser
函数的示例:所以看起来像这样:
let query = function( sql, values ) {
return new Promise(( resolve, reject ) => {
pool.getConnection(function(err, connection) {
if (err) {
resolve( err )
} else {
connection.query(sql, values, ( err, rows) => {
connection.release()
if ( err ) {
reject( err )
} else {
resolve( rows )
}
})
}
})
})
}
let findAUser = function (id) {
let _sql = `
SELECT * FROM user where id = ?
`
return query(_sql, [id])
}