我有一段代码,对我来说总是不起作用。有时候它会返回有关数据库锁定的错误,有时还会涉及连接。如何使用SQLiteCommand进行插入查询?
这是代码:
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))
{
sqCommand.CommandText = sql;
int rows = sqCommand.ExecuteNonQuery();
return !(rows == 0);
}
}
finally
{
myConn.Close();
}
我做什么了?
错误是:
No connection associated with this command
в System.Data.SQLite.SQLiteCommand.InitializeForReader() в System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior
behavior) в System.Data.SQLite.SQLiteCommand.ExecuteNonQuery(CommandBehavior behavior) в System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
在行:
int rows = sqCommand.ExecuteNonQuery();
个人而言,我会改变你的代码的'finally'部分是一个'catch',你不需要调用'myConn.Close()'您目前是'使用的内(){}'所以它会自动处理该对象,当你离开使用代码块..也检出这篇文章关于Sqlite锁定https://stackoverflow.com/questions/1800174/how-do-i-stop-the -the-database-file-is-locked-exception – MethodMan
好吧,试试吧,但不要以为这是理由。我现在会发布错误 – OPV
你的错误似乎与当前的代码无关......你并没有在那个Insert语句中调用ExecuteReader ..也试着做一个sqlcommand.Commit()通过你所有的代码进行搜索找到你在调用'ExecuteReader'的地方。 – MethodMan