2017-11-10 117 views
1

我有一段代码,对我来说总是不起作用。有时候它会返回有关数据库锁定的错误,有时还会涉及连接。如何使用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(); 
+1

个人而言,我会改变你的代码的'finally'部分是一个'catch',你不需要调用'myConn.Close()'您目前是'使用的内(){}'所以它会自动处理该对象,当你离开使用代码块..也检出这篇文章关于Sqlite锁定https://stackoverflow.com/questions/1800174/how-do-i-stop-the -the-database-file-is-locked-exception – MethodMan

+1

好吧,试试吧,但不要以为这是理由。我现在会发布错误 – OPV

+0

你的错误似乎与当前的代码无关......你并没有在那个Insert语句中调用ExecuteReader ..也试着做一个sqlcommand.Commit()通过你所有的代码进行搜索找到你在调用'ExecuteReader'的地方。 – MethodMan

回答

2

你忘了assignConnectionCommand

No connection associated with this command

using(SQLiteCommand sqCommand = new SQLiteCommand(sql)) 

应该TH我们是:

using(SQLiteCommand sqCommand = new SQLiteCommand(sql, myConn)) 
+0

它仍然给我一个错误:当我执行此操作时,“数据库被锁定” – OPV

+0

在行'int rows = sqCommand.ExecuteNonQuery();' – OPV

+0

我会标记,但它是问题的一部分。 – OPV