直接上代码:
/** * 设置mysql连接,返回连接实例。 连接格式:账户:密码@数据库地址/具体数据库名称 * **/ const setConnect=()=>{ const sequelize = new Sequelize( `mysql://${你的mysql地址 }`, { logging: (...msg) => Logger.INSTANCE.info(...msg), timezone: "+08:00", } ); return sequelize } /** * 构建实例 **/ build_my_model() { const sequelize =setConnect() const my_model = sequelize.define( "my_table,表名", { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, name: { type: DataTypes.INTEGER, }, age: { type: DataTypes.INTEGER, } }, { freezeTableName: true, // 禁用表名复数化 timestamps: false, // 禁用 createdAt 和 updatedAt 字段 } ); return my_model; } /** * 批量插入方法 **/ async add_people_list(list) { const batchSize = 100; // 每批插入的条数,可以设置为配置项 const totalBatches = Math.ceil(list.length / batchSize); const dataArray = list.map((issueItem) => ({ name: 张三, age: 18 })); for (let i = 0; i < totalBatches; i++) { const start = i * batchSize; const end = start + batchSize; const batch = dataArray.slice(start, end); try { const my_model = this.build_my_model(); await my_model.bulkCreate(batch, { validate: true, // 可选:在插入前验证数据 // 其他选项 }); Logger.INSTANCE.info(`Batch ${i + 1} inserted successfully.`); } catch (error) { Logger.INSTANCE.error(`Error inserting batch ${i + 1}:`, error); } } }
标签:const,nodejs,my,batchSize,mysql,model,sequelize From: https://www.cnblogs.com/llcdbk/p/18336306