• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

数据库被锁定sqCommand.ExecuteNonQuery()?

c/c++ 来源:OPV 6次浏览

我有以下代码:数据库被锁定sqCommand.ExecuteNonQuery()?

string sql = String.Format("insert into {0}({1}) values({2});", tableName, columns, values); 
SQLiteConnection myConn = null; 
try 
{ 
    myConn = new SQLiteConnection(dbConnection); 
    myConn.Open(); 

    using(SQLiteCommand sqCommand = new SQLiteCommand(sql, myConn)) 
    { 
     sqCommand.CommandText = sql; 
     int rows = sqCommand.ExecuteNonQuery(); 
     return !(rows == 0); 
    } 
} 
finally 
{ 
    myConn.Close(); 
} 

它总是返回一个错误:在Database is locked行:

int rows = sqCommand.ExecuteNonQuery(); 

WHU不会发生?


===========解决方案如下:

我敢打赌,数据库连接是离开的时候sqCommand.ExecuteNonQuery()方法执行开放的地方(这锁仍适用于以前的连接),因此你需要通过包装SQLiteConnection实例与using语句块这样的重构:

string sql = String.Format("insert into {0}({1}) values({2});", tableName, columns, values); 
using (SQLiteConnection myConn = new SQLiteConnection(dbConnection)) 
{ 
    try 
    { 
     myConn.Open(); 

     using (SQLiteCommand sqCommand = new SQLiteCommand(sql, myConn)) 
     { 
      sqCommand.CommandText = sql; 
      int rows = sqCommand.ExecuteNonQuery(); 
      return !(rows == 0); 
     } 
    } 
    catch (Exception e) 
    { 
     // do exception handling 
    } 
} 

参考:

Writing to a database file


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)