我有一张查询表:
[...]
for j = 0 to objRS.fields.count - 1
response.write(objRS.fields(j).name & " = " & objRS.fields(j).value)
next
我想在此表中为数组中的每个元素存储一条新记录:
CREATE TABLE technologies (
technologyName VARCHAR(50) NOT NULL PRIMARY KEY
);
因此生成的表格如下所示:
var values = ['Grunt', 'Gulp'];
如何使用Node执行此操作?
更新
我知道我可以这样做:
+----------------+
| technologyName |
+----------------+
| Grunt |
+----------------+
| Gulp |
+----------------+
我用原始数组尝试了这个但是它不起作用。如何将简单数组转换为更复杂的数组?
答案 0 :(得分:2)
如果你想使用"?"为了逃避您的值并避免SQL注入,mysqljs接受嵌套数组进行批量插入。 所以你的更新的答案是:
var valuesNestedArray = [];
for(var v in values ) {
valuesNestedArray.push([values[v]]);
}
var sql = "INSERT IGNORE INTO technologies (technologyname) values ?";
connection.query(sql, [valuesNestedArray], function(err) {
if (err) throw err;
});
答案 1 :(得分:1)
您可以一次插入多个内容......
来自mysql文档(https://dev.mysql.com/doc/refman/5.5/en/insert.html)
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
所以对你:
insert into technologies (technologyname) values ('grunt'),('gulp')
var sql = "insert into technologies (technologyname) values ";
for(var v in values)
sql += "('" + connection.escape(values[v]) + "'),";
sql = sql.substr(0,sql.length-1); // take off the last comma since we added one after each value