2012-12-26 54 views
1

我使用http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki版本1.0.82.0SQLite的報告,即使該行插入

當我插入一行像這樣插入查詢錯誤:

"INSERT INTO [testtable] (col1,col2) values ('','')" 

我總是從SQLiteCommand.ExecuteNonQuery();從哪裏弄來的1結果它應該返回0(OK)或101(DONE)。我知道該行插入得很好,因爲每次運行該方法時自動遞增值都會增加。

readonly object _threadlock = new object(); 
readonly string _file; 

public CSQLite(string file) 
{ 
    _file = file; 
} 

private SQLiteConnection _sqlCon; 
private SQLiteCommand _sqlCmd; 
private SQLiteDataAdapter _db; 

private void SetConnection() 
{ 
    lock (_threadlock) 
    { 
     _sqlCon = new SQLiteConnection(String.Format("Data Source={0};Version=3;New=False;Compress=True;", _file)); 
    } 
} 

public int SimpleInsertAndGetlastID(out int id) 
{ 
    lock (_threadlock) 
    { 
     SetConnection(); 
     _sqlCon.Open(); 

     //Execute 
     _sqlCmd = _sqlCon.CreateCommand(); 
     _sqlCmd.CommandText = "INSERT INTO [testtable] (col1,col2) values ('','')"; 
     var res = _sqlCmd.ExecuteNonQuery(); 

     //Get id 
     _db = new SQLiteDataAdapter("select last_insert_rowid();", _sqlCon); 
     var ds = new DataSet(); 
     _db.Fill(ds); 
     DataTable dt = ds.Tables[0]; 
     var val = dt.Rows[0][0].ToString(); 

     Int32.TryParse(val, out id); 

     _sqlCon.Close(); 
     return res; 
    } 
} 

測試:

/// <summary> 
///A test for SimpleInsertAndGetlastID 
///</summary> 
[TestMethod()] 
public void SimpleInsertAndGetlastIDTest() 
{ 
    var file = "dbs\\test.db"; 
    var target = new CSQLite(file); 
    var id = -1; 
    var res = -1; 

    try 
    { 
     res = target.SimpleInsertAndGetlastID(out id); 
    } 
    catch (Exception ex){/*Breakpoint*/} 

    Assert.IsTrue(id > 0); //id gets +1 every time the test is run so the row *is* getting inserted 
    Assert.IsTrue(res==0||res==101); //Res is always 1 for some reason 
} 

創建表(如果這就是問題所在):

public List<string> Columns { get; set; } 

if (!File.Exists(_dbFile)) 
    SQLiteConnection.CreateFile(_dbFile); 

var fieldqry = ""; 
var count = 0; 
Columns.ForEach((field) => 
    { 
     count++; 

     fieldqry += String.Format("[{0}] TEXT NULL", field); 

     if (count < Columns.Count) 
      fieldqry += ","; 
    }); 

var qry = String.Format("CREATE TABLE IF NOT EXISTS [{0}](" + 
         "[ID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + 
         "{1}" + 
         ");", TableName, fieldqry); 

var sql = new CSQLite(_dbFile); 
var res = sql.Execute(qry); 
if(res!=SqLiteErrorCodes.SQLITE_OK) 
    throw new SqLiteImplementationException("Query failed."); 

,其中,列是new List<string> { "col1", "col2" } };

誰能告訴我我做錯了什麼?

回答

3

ExecuteNonQuery()不會返回SQLite錯誤代碼,它會返回受查詢影響的行數。如果你插入一行,如果操作成功,1聽起來像預期的結果。

+1

哦,我明白了! 1將是完美的結果。但是,那麼返回所有這些[非常有用的代碼](http://www.sqlite.org/c3ref/c_abort.html)的方法是什麼? - 沒關係:http://stackoverflow.com/questions/11223044/retreiving-error-codes-from-sqlite-when-using-executenonquery – natli

3

從的ExecuteNonQuery結果concidered爲「受影響的行數」,而不是一個錯誤代碼:-)