B
B
Boris the Animal2021-05-15 00:55:08
SQLite
Boris the Animal, 2021-05-15 00:55:08

Dapper and SQLite. Checking whether the table exists in the database does not work. How to fix?

public class Storage
    {
        public Storage()
        {
        }

        public async Task Initialize()
        {
            string connectionString = $"FileName=Data.sqlite";

            SqliteConnection connection = null;
            try
            {
                await Task.Run(async () =>
                {
                    connection = new SqliteConnection(connectionString);
                    connection.Open();
                    
                    var parameters = new { TableName = "options" };
                    int result = await connection.ExecuteAsync(
                           "SELECT count(*) FROM sqlite_master WHERE type='table' AND [email protected]", parameters);

                    if (result < 1)
                    {
                        result = await createTables(connection);
                    }
                });
            }
            finally
            {
                if (connection is not null)
                {
                    await connection.DisposeAsync();
                }
            }
        }

        private async Task<int> createTables(SqliteConnection connection)
        {
            return await connection.ExecuteAsync(@"
create table options
(
  parameter_name text not null,
  value text not null
);
create unique index options_parameter_name_uindex
  on options (parameter_name);");
        }
    }


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <LangVersion>9</LangVersion>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Dapper" Version="2.0.90" />
    <PackageReference Include="Microsoft.Data.Sqlite" Version="5.0.6" />
  </ItemGroup>

</Project>


The query always returns -1. Why and how to fix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ananiev, 2021-05-15
@Casper-SC

Just use the CREATE TABLE IF NOT EXISTS construct

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question