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

개인적으로 나는'catch'로 코드의'finally' 섹션을 바꿀 것하고'myConn.Close를 호출 할 필요는 없다() {}'그래서 당신이 사용하는 코드 블록을 떠날 때 자동으로 해당 개체를 처리합니다 ..이 체크 아웃 Sqlite 잠금에 대한이 게시물 https://stackoverflow.com/questions/1800174/how-do-i-stop-the -the-database-file-is-locked-exception – MethodMan

+1

좋아요, 시도 할게요,하지만 그게 이유라고 생각하지 않습니다. 내가 지금 오류를 게시 할 것입니다 – OPV

+0

당신의 오류는 현재 코드와 아무 상관이없는 것 같습니다 .. 당신은 그 명령문에서'ExecuteReader'를 호출하지 않습니다 .. 또한 sqlcommand.Commit()를 시도하여 모든 코드를 검색합니다. 'ExecuteReader'를 호출하는 곳을 찾으십시오. – MethodMan

답변

2

당신은 assign에 잊고 ConnectionCommand받는 사람 :

No connection associated with this command

using(SQLiteCommand sqCommand = new SQLiteCommand(sql)) 

은 토륨한다 우리는 수`당신이`사용하여 내부 현재) (

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

여전히이 작업을 수행 할 때 "데이터베이스가 잠겨 있습니다"라는 오류 메시지가 표시됩니다. – OPV

+0

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

+0

줄에 표시하지만 질문의 일부입니다. – OPV

관련 문제