in

System.Data.SQLite

An open source ADO.NET provider for the SQLite database engine

Check if table exists

Last post 12-08-2009 8:53 AM by shawty_ds. 4 replies.
Page 1 of 1 (5 items)
Sort Posts: Previous Next
  • 06-04-2007 3:28 AM

    Check if table exists

    Hi

    Trying to create my first application with SQLite. I have some experience with MySQL.

    Used the sources in the example here to figure out how to access a database. But I now have a question:
    If a new file is created, then this one would be empty. So I need to create the tables. If it is not empty, than all tables should be in there already.

    How do I figure out, which one is the case? Or in other words: How can I figure out, if a table exists?

    I now that you use "Create table if not exists ...". But it doesn't make sense to me trying always to create the table. Is there a better way?

    Thanks for your help.
    Sebastian
  • 06-04-2007 6:33 AM In reply to

    • bfr
    • Top 75 Contributor
    • Joined on 01-20-2006
    • Posts 18

    Re: Check if table exists

    Check out the connection GetSchema method.  For example:

    conn.GetSchema("Tables").Select("Table_Name = 'mumble'");

  • 06-06-2007 8:10 AM In reply to

    Re: Check if table exists

    Thanks. That helps.

    Needed some time to figure out, what kind of object conn.GetSchema returns. It seems to me it is an array of System.Data.DataRow. Hope this is right (well, it works).
  • 09-23-2009 10:07 PM In reply to

    Re: Check if table exists

    also you can use next query SELECT name FROM sqlite_master WHERE name='table_name' if reader has rows then table is exists
  • 12-08-2009 8:53 AM In reply to

    Re: Check if table exists

     Just my tuppence worth, but I thought I add it anyway, this is the function I use.  (You'll need a "using System.Data.SQLite" clause at the top of your code)

     

        public Boolean doesTableExist(SQLiteConnection theDatabase, String tableName)
        {
          SQLiteCommand cmd = new SQLiteCommand(theDatabase);
          cmd.CommandText = "SELECT name FROM sqlite_master WHERE name='" + tableName + "'";
          SQLiteDataReader rdr = cmd.ExecuteReader();
          if (rdr.HasRows)
            return true;
          else
            return false;
        }
     

    regards

     

    shawty

     

Page 1 of 1 (5 items)
Powered by Community Server (Commercial Edition), by Telligent Systems