即使插入了行,SQLite报告也会插入查询错误

时间:2012-12-26 23:21:11

标签: c# sqlite

我正在使用http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki版本1.0.82.0

当我插入一行时:

"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" } };

谁能告诉我我做错了什么?

2 个答案:

答案 0 :(得分:3)

ExecuteNonQuery()不返回SQLite错误代码,它返回受查询影响的行数。如果要插入一行,如果操作成功,则1听起来像预期的结果。

答案 1 :(得分:3)

ExecuteNonQuery的结果被视为“受影响的行数”而不是错误代码: - )