C#中使用SQLiteTransaction批量插入数据至数据库
- 使用事务(Transaction):在插入大量数据时,可以使用事务来提高插入数据的效率。在C#中,可以使用SQLiteTransaction类来开启一个事务,然后使用SQLiteCommand类来执行批量插入操作,最后提交事务。
示例代码如下:
string sql; string tmpTabelName = "dinners"; string id, name, devicename, department, date, time, flag, type, authortype, userid; string connectionString = DBHelperSQLite.connectionString; //导入前先清空 sql = "delete from dinners"; DBHelperSQLite.ExecuteSql(sql); //批量插入 using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { connection.Open(); using (SQLiteTransaction transaction = connection.BeginTransaction()) { using (SQLiteCommand command = connection.CreateCommand()) { command.Transaction = transaction; for (int i = 0; i < dataGridView1.RowCount; i++) { name = Convert.ToString(dataGridView1.Rows[i].Cells["姓名"].Value).Trim(); devicename = Convert.ToString(dataGridView1.Rows[i].Cells["设备"].Value).Trim(); department = Convert.ToString(dataGridView1.Rows[i].Cells["部门"].Value).Trim(); date = Convert.ToString(dataGridView1.Rows[i].Cells["日期"].Value).Trim(); time = Convert.ToString(dataGridView1.Rows[i].Cells["时间"].Value).Trim(); flag = Convert.ToString(dataGridView1.Rows[i].Cells["通行标签"].Value).Trim(); type = Convert.ToString(dataGridView1.Rows[i].Cells["识别类型"].Value).Trim(); authortype = Convert.ToString(dataGridView1.Rows[i].Cells["权限类型"].Value).Trim(); userid = Convert.ToString(dataGridView1.Rows[i].Cells["用户ID"].Value).Trim(); //判断各个刷卡时间段; if (time.Length > 2) flag = time.Substring(0, 2); if (",07,08".IndexOf(flag) > 0) flag = "早"; if (",10,11,12".IndexOf(flag) > 0) flag = "中"; if (",16,17".IndexOf(flag) > 0) flag = "晚"; if (",20,21".IndexOf(flag) > 0) flag = "小"; if (",23,00,01".IndexOf(flag) > 0) flag = "大"; if (",03,04,".IndexOf(flag) > 0) flag = "大"; sql = "Insert into " + tmpTabelName + " (name,devicename,department,date,time,flag,type,authortype,userid)"; sql += " values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')"; sql = String.Format(sql, name, devicename, department, date, time, flag, type, authortype, userid); command.CommandText = sql; command.ExecuteNonQuery(); command.Parameters.Clear(); } transaction.Commit(); } } } MessageBox.Show("数据保存完成!");
活到老,学到老。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性