1

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

当我像这样插入一行时:

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

我总是从SQLiteCommand.ExecuteNonQuery();应该返回 0(OK)或 101(DONE)的地方得到 1 的结果。我知道该行插入得很好,因为每次运行该方法时自动增量值都会增加。

班上

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

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

4

2 回答 2

3

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

于 2012-12-26T23:23:41.207 回答
3

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

于 2012-12-26T23:28:13.210 回答