更新期间的C#SQLite数据库

时间:2017-02-09 06:40:27

标签: c# .net sqlite

我的SQLite查询在我的ExecuteNonQuery()中挂起,然后在下面的WriteToDB()中。它似乎只在UPDATE期间锁定并且INSERT没有问题。这只在一个线程中运行。当它挂起时,我可以看到在SQLite数据库目录中创建的日志就好像它一直在尝试写入一样。它抛出SQLiteException,ErrorCode = 5,ResultCode = Busy。

    public String WriteToDB()
    {
        String retString = "";

        //see if account exists with this email
        String sql = "";
        bool aExists = AccountExists();

        if (!aExists)
        {
            sql = "INSERT INTO accounts (email, password, proxy, type, description) VALUES ('" + Email + "', '" + Password + "', '" + Proxy + "', 'dev', '" + Description + "');";
            retString = "Added account";
        }
        else
        {
            sql = "UPDATE accounts SET password='" + Password + "', proxy='" + Proxy + "', description='" + Description + "' WHERE (email='" + Email + "' AND type='dev');";
            retString = "Updated account";
        }

        using (SQLiteConnection dbconn = new SQLiteConnection("Data Source=" + Form1.DBNAME + ";Version=3;"))
        {
            dbconn.Open();
            using (SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbconn))
            {
                sqlcmd.ExecuteNonQuery(); //this is where it locks. Only on update.
            }
        }
        return retString;
    }

    //Test to see if Email exists as account
    public bool AccountExists()
    {
        int rCount = 0;
        String sql = "SELECT COUNT(email) FROM accounts WHERE email='" + Email + "' AND type='dev';";
        using (SQLiteConnection dbconn = new SQLiteConnection("Data Source=" + Form1.DBNAME + ";Version=3;"))
        {
            dbconn.Open();
            using (SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbconn))
            {
                rCount = Convert.ToInt32(sqlcmd.ExecuteScalar());
            }
        }
        if (rCount > 0)
            return true;
        return false;
    }

1 个答案:

答案 0 :(得分:1)

哦,男人,我感到愚蠢。我以为我发布了所有相关代码,但我发布的所有代码都运行得很好。我有:

SQLiteDataReader dbReader = sqlcmd.ExecuteReader()

而不是

using (SQLiteDataReader dbReader = sqlcmd.ExecuteReader())

在另一个功能中。我认为这是UPDATE的问题,因为那是发生锁定的地方。感谢您的回复,希望这些提醒提醒大家第一次使用带有SQLite的using()块!