sqlite 只有在连接打开时才能调用ExecuteScalar

8dtrkrch  于 2023-01-26  发布在  SQLite
关注(0)|答案(2)|浏览(145)

受保护覆盖异步空OnAppearing(){

dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "OrderappDb.db");
        bool DbExists = File.Exists(dbPath);

        var connect = new SqliteConnection("Data Source=" + dbPath);
     

    private bool tableExists(SqliteConnection connection, string tableName)
    {
        dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "OrderappDb.db");
        var connect = new SqliteConnection("Data Source=" + dbPath);
        connection = connect;
        try
        {
            if (connection.State == System.Data.ConnectionState.Closed)

                connection.Open();
            using (cmd = new SqliteCommand(connection.ToString()))
            {
                //sqlite_master

                cmd.CommandText = $"Select Count(*) from sqlite_master where type='table' and name='{tableName}';";

                object result = cmd.ExecuteScalar();
                //connection.Open();
                int resultCount = Convert.ToInt32(result);
                if (resultCount > 0)
                    return true;
                connection.Close();
                //  sqlite_master
            }
            return false;
        }

        catch (Exception ex)
        {
            return false;
        }


    }

我正在sqlite中创建表并访问该表。获取,ExecuteScalar只能在连接打开时调用。我不明白为什么会出现上述错误。请帮助我的代码段。

cbjzeqam

cbjzeqam1#

对于SqliteCommand的使用方式没有重载。

Using SqliteCommand cmd = new SqliteCommand(yourSqlString, connection) {
    Integer val = cmd.executeScalar();
}

https://learn.microsoft.com/en-us/dotnet/api/microsoft.data.sqlite.sqlitecommand?view=msdata-sqlite-7.0.0#constructors

wko9yo5t

wko9yo5t2#

SqlCommand.ExecuteReader方法将CommandText发送到连接并构建SqlDataReader。因此,需要connection.Open();方法来打开连接,这就是为什么ExecuteScalar方法只能在连接打开时调用。

相关问题