how to check if a table exists in C#

Viewed 12894

First, let me tell you I checked a bunch of the "How to check if a table exists in ...". I nevertheless need some more information about the query

SELECT name FROM sqlite_master WHERE type='table' AND name='table_name';

I supposed I had to change the names "sqlite_master" and "table_name", and here is my code

// a static function of the public class "SqliteBase"
public static void CreerBase(string dataSource)
{
    SQLiteConnection connection = new SQLiteConnection();

    connection.ConnectionString = "Data Source=" + dataSource;
    connection.Open();
    SQLiteCommand command = new SQLiteCommand(connection);

    // Create table if it does not exist
    command.CommandText = "CREATE TABLE IF NOT EXISTS beispiel ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name VARCHAR(100) NOT NULL);";
    Console.WriteLine("La Table a bien été créée");
    command.ExecuteNonQuery();
    command.Dispose();
    connection.Close();
    connection.Dispose();
}

and the unit test function :

[TestMethod]  
public void LaCreationBaseMarche()
{
    string dataSource = "beispiel.db";
    SqliteBase.CreerBase(dataSource);
    SQLiteConnection connection = new SQLiteConnection();

    connection.ConnectionString = "Data Source=" + dataSource;
    connection.Open();
    SQLiteCommand command = new SQLiteCommand(connection);
    command.CommandText = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'beispiel';";
    SQLiteDataReader reader = command.ExecuteReader();
    Assert.Equals("beispiel", reader[0].ToString());
    reader.Close();
    reader.Dispose();

    command.Dispose();

}

My problem is : the command.executeReader() of the test method returns me a "null" reader, and of course i got an error when I try to do reader[0].. Did I misused the query ?

EDIT : Ok, I though I had to use the name of the file ^^. Now I changed it, but it still doesn't work (same error). I also changed the name "exemple.db" in "beispiel.db". I updated my code :)

Thank you in advance for your answers :)

4 Answers

I did the following to check if a table already exists in the database

public static bool tableAlreadyExists(SqliteConnection openConnection, string tableName)
{
  var sql = 
  "SELECT name FROM sqlite_master WHERE type='table' AND name='"+tableName +"';"; 
  if(openConnection.State == System.Data.ConnectionState.Open)
  {   
        SqliteCommand command = new SqliteCommand(sql, openConnection);
        SqliteDataReader reader =command.ExecuteReader();
        if(reader.HasRows)
        {
            return true;
        }
        return false;
    }else{
        throw new System.ArgumentException("Data.ConnectionState must be open");
    }
}
Related