我正在使用以下Node.js代码。看来我可以读取我的数据库,但是在写入数据库时却非常困难。任何帮助将不胜感激,这令人难以置信。
我已经尝试了INSERT SQL语句的多种变体,但都没有成功...在此先感谢您的任何建议。
//**Query PostGres database...
const url = require('url')
var pg = require('pg');
const params = url.parse(process.env.DATABASE_URL);
const auth = params.auth.split(':');
const config = {
user: auth[0],
password: auth[1],
host: params.hostname,
port: params.port,
database: params.pathname.split('/')[1],
ssl: false
};
var pool = new pg.Pool(config);
var conString = "postgres://user:password@localhost:5432/mydatabase";
var client = new pg.Client(conString);
const query = {
text: "SELECT * FROM users WHERE name = $1 AND cred = $2",
values: [String(req.body.usr), String(req.body.pword)]
};
var written = "INSERT INTO users(name, cred, status, in, out, service, lucky) VALUES ?";
var writes = [String(req.body.usr), String(req.body.pword), 'active', 'test', 'pending', 'both', -1];
pool.connect(function(err,client,done) {
if(err){
console.log("not able to get connection "+ err);
res.status(400).send(err);
}
client.query(query, function(err, result) {
//call `done()` to release the client back to the pool
done();
if(err){
console.log(err);
res.status(400).send(err);
}
if (typeof result.rows[0] === "undefined") {
console.log("No user/password determined in DB for login attempt");
} else {
if (result.rows[0].status === "active") {
console.log("User is determined to be ACTIVE in database");
//...for WRITING into database...!
client.query(written, [writes], function (err, result) {
console.log("I am here now after writing);
});
} else {
console.log("User is determined to be INACTIVE in database");
} //User ACTIVE...OR NOT...
} //user/password is 'undefined' (NOT found in database)...OR NOT
console.log(result.rows[0]);
});
});