我有一组客户对象,我希望将其插入到 SQL 数据库中。 从请求数据中检索客户对象。
我正在使用 Tedious 处理请求,并使用 Tedious Connectionpool 以便同时拥有多个连接。
当遍历对象时,我在尝试插入时遇到错误,错误是
{ [RequestError: Violation of PRIMARY KEY constraint `'PK__Customer__A4AE64D873A5400C'. Cannot insert duplicate key in object 'dbo.Customer'. The duplicate key value is (2).]`
请注意,此时我在请求中只发送了 3 个对象。在我看来,它只是最后一个被处理和插入的对象。但是由于我不熟悉使用 Node.js 的繁琐,所以我无法发现我的错误。有什么建议吗?
router.post('/',jsonParser, function(req, res) {
var customers = req.body.customers;
var companies = req.body.companies;
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
var config = {
userName: '*************',
password: '*************',
server: '***********.database.windows.net',
// When you connect to Azure SQL Database, you need these next options.
options: {encrypt: true, database: '*******'}
};
var poolConfig = {
min: 1,
max: 3,
log: true
};
var pool = new ConnectionPool(poolConfig, config);
for (var i = 0; i < customers.length; i++) {
console.log('Inserting '+customers[i].firstname);
var firstname = customers[i].firstname;
var count = i;
pool.acquire(function (err, connection) {
if (err)
console.error(err);
//use the connection as normal
var request = new Request("INSERT INTO dbo.Customer" +
" (Firstname,CustomerId)" +
"VALUES" +
" (@Firstname,@CustomerId);", function (err, rowCount) {
if (err)
console.error(err);
console.log('rowCount: ' + rowCount);
//release the connection back to the pool when finished
connection.release();
});
request.addParameter('Firstname', TYPES.VarChar,firstname);
request.addParameter('CustomerId', TYPES.Int, count);
request.on('row', function (columns) {
console.log('value: ' + columns[0].value);
});
connection.execSql(request);
});
pool.on('error', function (err) {
console.error(err);
});
}
});
最佳答案
变量 count
和 firstName
的范围是全局的。当 pool.acquire(
函数 get 执行完时,for 循环已经完成,它会两次插入最后一个客户。一个可能的解决方案是在 for 循环中放置一个匿名函数,例如(它不会但必须是匿名的)
for (var i = 0; i < customers.length; i++) {
(function(count, firstName) {
...do insert here...
}(i, customers[i].firstname));
}
关于javascript - 使用 Node.js 和 Tedious 插入多条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33732297/