我发现了一些例子,可以通过执行以下操作直接将对象插入DB:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'cccc.net',
user : 'username',
password : 'password',
});
var post = {srcUserID: userSrcID, destUserID: msg.userid, messageContent: msg.txt, messageSendDate:sendDate };
connection.query('INSERT INTO messages SET ?', post, function(err, result) {
});
但这适用于mysql模块,我有SQL Server作为我的数据库所以我使用
var SQL_DB = require('mssql');
有没有办法将对象直接插入到DB中,以同样的方式使用mysql模块。
答案 0 :(得分:0)
查看node-mssql v4文档,他们使用回调函数作为示例:
const sql = require('mssql');
const config = {
user: '...',
password: '...',
server: 'localhost',
database: '...',
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000
}
};
const pool = new sql.ConnectionPool(config);
const transaction = new sql.Transaction(pool);
transaction.begin(err => {
// ... error checks
const request = new sql.Request(transaction)
request.query('insert into mytable (mycolumn) values (12345)', (err, result) => {
// ... error checks
transaction.commit(err => {
// ... error checks
console.log("Transaction committed.")
})
})
})
编辑:node-mssql似乎使用request.input来转义值,但是不接受js对象,你可以快速制作自己的:
sql.connect(config, err => {
var post = {srcUserID: userSrcID, destUserID: msg.userid, messageContent: msg.txt, messageSendDate:sendDate };
const request = new sql.Request();
let cols = [];
let inputs = [];
for(let k in post) {
request.input(k, post[k]);
cols.push(k);
inputs.push('@' + k);
}
let query = `insert into messages (${cols.toString()}) values (${inputs.toString()})`;
request.query(query, (err, result) => {
//stuff here
});
});