2017-11-10 270 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