我编写了以下代码,通过使用for循环读取JSON来插入记录集。
这是我的代码:
的node.js:
var MySQLHelper = {
composeQuery:
function(stpName, paramArray) {
var statement = "call " + stpName + "(";
for(var i = 0, len = paramArray.length; i < len; ++i) {
var p = paramArray[i];
statement += "'" + p +"'"; // add a parameter
if (i != len-1 ) {
statement += ","; // add a parameter seperater
}
else {
statement += ")"; // closing statement
}
}
return statement;
}
}
Dam.prototype.InsertPreset = function(taskInfo) {
// Compose a dynamic mySQL query statement for inserting a preset
for(var i=0;i<taskInfo.presetList.length;i++){
var insert_preset_statement =MySQLHelper.composeQuery('preset_insert',
[ taskInfo.presetList[i].Name,
taskInfo.presetList[i].Category,
taskInfo.presetList[i].GUID
]);
this.connection.query(insert_preset_statement, function(err, result) {
if (err) {
console.log('db error:' + err);
}
else {
console.log('db task : Successfully Added');
}
});
}
}
JSON:
{
"presetList": [
{
"Name": "AARAMBAMTestfile",
"Category": "Harmonic",
"GUID": "ABC10203"
},
{
"Name": "ENDHIRANTestfile",
"Category": "Harmonic",
"GUID": "DRU03472"
}
]
}
为此,我在MySql中编写了一个普通的插入存储过程,如下所示:
MySQL SP:
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `preset_insert`(
IN p_Name varchar(50),
IN p_Category varchar(50),
IN p_GUID varchar(50)
)
BEGIN
INSERT INTO Preset
(
PresetName,
PresetCategory,
PresetGUID,
)
VALUES
(
p_Name,
p_Category,
p_GUID
);
END
上述代码工作正常。但我不想使用for循环逐个插入。 但是我没有使用for循环来做这件事,而是希望一次使用insert select语句进行批量插入。如何使用node.js?
执行此操作答案 0 :(得分:1)
您可以像下面这样进行单个插入查询,并调用查询来执行。
function insertValues(ob) {
return "('" + ob.Name + "','" + ob.Category + "','" + ob.GUID + ")";
}
var queryStr = "INSERT INTO `Preset` (`PresetName ` ,`PresetCategory `, `PresetGUID `)
VALUES ";
var valueStrs = [];
for(var i=0;i<taskInfo.presetList.length;i++){
valueStrs.push(insertValues(taskInfo.presetList[i]));
}
queryStr += valueStrs.join(',');
this.connection.query(queryStr, function(err, result) {
if (err) {
console.log('db error:' + err);
}
else {
console.log('db task : Successfully Added');
}
});
答案 1 :(得分:0)
我尝试了这段代码并且工作正常:
var PresetData = [taskInfo.presetList.length];
for( var i = 0; i < taskInfo.presetList.length; i++){
PresetData[i] = [ taskInfo.presetList[i].Name, "" + taskInfo.presetList[i].Category, "" + taskInfo.presetList[i].GUID ];
}
console.log("PresetData: " + JSON.stringify(PresetData));
this.connection.query( "INSERT INTO Preset (PresetName, PresetCategory, PresetGUID) VALUES ?", [PresetData], function(err, result) {
});