我们知道MySQL支持批量添加记录,用法也比较简单,不过需要编码需要注意一下,因为很容易搞错
var jargs = require('./argspw.json');
const mysql = require("mysql"); const mysqlpool= mysql.createPool({host:jargs.mysqlip,user:jargs.mysqluser,password:mycrypt.decrypt(jargs.mysqlpw),//配置文件里口令密文解密port:jargs.mysqlport,database:jargs.mysqldatabase});
const addrcs='insert into table1(id,name,age,school) values ?'
var rclist=[["id1","name1","age1","sc1"],["id2","name2","age2","sc2"],["id3","name3","age3","sc3"]]//注意每个记录是一个list,这些记录又是一个大list的成员
mysqlpool.getConnection((errmpgc, mysqlconn)=> { if (errmpgc) { console.log("建立连接失败"); } else {mysqlconn.query(addrcs,[rclist],(erriw1,results1)=> { //注意在rclist外又包裹了一对方括号if (erriw1) { console.log("SQL执行失败"); console.log(erriw1.message); }else { console.log("SQL执行成功"); }mysqlconn.release();}});
update语句是不支持批量提交的,不过可以用replace into或者insert into on duplicate key update曲线救国。需要注意的是要在table中定义主键,replace into是对重复记录先删后填加,后者是更改,如果values不全的话,前者会丢失这些信息,后者则保留这些信息。所以推荐采用后一种方法。
const updatercs='insert into table1(id,name,school) values ? on duplicate key update school=values(school),name=values(name)'
var rclist=[["id1","name11","pku"],["id2","name22","pku"],["id3","name33","pku"]]
mysqlpool.getConnection((errmpgc, mysqlconn)=> { if (errmpgc) { console.log("建立连接失败"); } else {mysqlconn.query(updatercs,[rclist],(erriw1,results1)=> { if (erriw1) { console.log("SQL执行失败"); console.log(erriw1.message); }else { console.log("SQL执行成功"); }mysqlconn.release();}});