SQLite Database Connection in C# - Example Code

This is an example code of how I connect to an SQLite database. But before you do the codes or scripts of connecting to sqlite, you will have to download the sqlite libraries for it to be working.


You can download System.Data.SQLite so that you can connect to sqlite database. All the classes used for sqlite are here in this library. Just search on System.Data.SQLite and install it on your computer.

Here is an example code of connecting to an SQLite Database

Aside from some c# namespaces, you will have to include sqlite library for c# to use it.

using System.Data.SQLite;

Then inside of your class, you can create objects from sqlite classes.

So for connecting to an SQLite database, here is an example bellow.

SQLiteConnection connection =  new SQLiteConnection("Data Source=C:\\mydatabase.sqlite");

SQLiteConnection conn;
SQLiteCommand cmd;
SQLiteDataReader reader; 

try
{
     conn = new SQLiteConnection("Data Source=C:\\mydatabase.sqlite");
     cmd = new SQLiteCommand();
     cmd.CommandText="select * from table";
     cmd.Connection=conn;
     reader=cmd.ExecuteReader();
    if(reader.HasRows)
    {
         while(reader.Read()){
               //manipulate for reader...
              // example:   int x = reader.GetInt32(0);
         }
     }
     reader.Close();
     conn.Close();
 }catch(Exception ex){
   //message for error connecting to sqlite database
}

The example above is tested and works well. Just try to test this code if you want to connect to an sqlite database file.

No comments:

Post a Comment