SQLite插入循环错误'SQLiteException:'数据库已锁定'

时间:2019-05-17 04:23:40

标签: c# sqlite datatable dapper

我正在尝试将DataTable插入SQLite表中,并且为此使用了foreach循环,但是它抛出错误SQLiteException: 'database is locked.

我试图对此进行搜索,并尝试disposeusing的联系

这是我的代码

public void Insert_to_db(DataTable data)
{
   foreach (DataRow row in data.Rows)
   {
           string alertTag = row["Alert Tag"].ToString();
           int group = Convert.ToInt32(row["Group"]);
           int line = Convert.ToInt32(row["Line"]);
           int task = Convert.ToInt32(row["Task"]);

           string sql = string.Format("insert into alert_tag (alert_tag, layer_group, line, task) values ('{0}','{1}','{2}','{3}')", alertTag, group, line, task);

           using (SQLiteConnection dbConn = new SQLiteConnection(Tools.SqliteConnString()))
           {
               using (SQLiteCommand command = new SQLiteCommand(sql, dbConn))
               {
                   dbConn.Open();
                   command.ExecuteNonQuery();
                   dbConn.Close();
               }
           }
   }
}

2 个答案:

答案 0 :(得分:0)

您需要更改代码,以便在 using (SQLiteConnection dbConn = new SQLiteConnection(Tools.SqliteConnString())) { using (SQLiteCommand command = new SQLiteCommand(sql, dbConn)) { dbConn.Open(); string alertTag; int group; int line; int task; string sql; foreach (DataRow row in data.Rows) { alertTag = row["Alert Tag"].ToString(); group = Convert.ToInt32(row["Group"]); line = Convert.ToInt32(row["Line"]); task = Convert.ToInt32(row["Task"]); sql = string.Format("insert into alert_tag (alert_tag, layer_group, line, task) values ('{0}','{1}','{2}','{3}')", alertTag, group, line, task); command.ExecuteNonQuery(); dbConn.Close(); } } } 内部进行循环:

locations = [["aus.1", "aus.2", "aus.3"],
             ["chn.1", "chn.2", "chn.3"],
             ["sat.1", "sat.2", "sat.3"]]
  1. 您可以考虑对从数据中获取的值进行一些完整性检查。您现在对SQL注入大开眼界。查看构建或使用parameters

  2. 我会调查Dapper或EF之类的良好ORM,以避免构建脆弱的插入语句

答案 1 :(得分:0)

因此,正如@JhonB所建议的那样,我决定使用dapper,但首先我必须convert将我的DataTabe放到对象列表中

private List<AlertTagModel> convert(DataTable dt)
{
   var convertedData = (from rw in dt.AsEnumerable()
                        select new AlertTagModel() {
                            alert_tag = Convert.ToString(rw["AlertTag"]),
                            layer_group = Convert.ToInt32(rw["Group"]),
                            line = Convert.ToInt32(rw["Line"]),
                            task = Convert.ToInt32(rw["Task"])
                            }).ToList();
   return convertedData;
}

然后使用dapper插入数据库

public void Insert_to_db(Object data)
{
     using (IDbConnection cnn = new SQLiteConnection(Tools.LoadConnectionString()))
     {
          cnn.Execute("insert into alert_tag (AlertTag, Layer_ID, Line_ID, Task_ID) values (@alert_tag, @layer_group, @line, @task)", data);
     }
}

解决了!