How can I access SQLite with C#?

14,562

Solution 1

You can not connect to sqlite db using SQLProvider classes. They are for sql server. You need to use SQLite provider classes.

Solution 2

SQLite in C# (requires System.Data.SQLite in references)

// Required references, after installing SQLite via Nuget
using System.Data.SQLite;
using System.Data.Common;

// Example usage in code...
SQLiteConnection db = new SQLiteConnection("Data Source=C:\LocalFolder\FooBar.db;FailIfMissing=True;");
db.Open();
using (SQLiteCommand comm=db.CreateCommand()) {
  comm.CommandText = requete_sql;
  IDataReader dr=comm.ExecuteReader();
  while (dr.Read())
  {
    //...
  }
}

Solution 3

There's an article on MSDN magazine about just that:

http://msdn.microsoft.com/en-us/magazine/ff898405.aspx

Solution 4

  1. Download the appropriate distribution from http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki
  2. Reference System.Data.SQLite.DLL in your project (this gives you the SQLiteConnection class)
  3. Connect with

    SQLiteConnection connection = new SQLiteConnection(@"DbLinqProvider=Sqlite;Data Source=Database.s3db"); 
    Main main = new Main(connection);
    

See https://code.google.com/p/dblinq2007/wiki/Installation#To_use_DbLinq for details.

Share:
14,562
Zakaria
Author by

Zakaria

Updated on June 11, 2022

Comments

  • Zakaria
    Zakaria almost 2 years

    I'm trying to get connected to my Sqlite database programmatically using C#/ASP.NET:

    string requete_sql = "SELECT * FROM USERS";
    connStr = @"Data Source=C:\LocalFolder\FooBar.db;";
    using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr)) {
    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(requete_sql,conn);
    conn.Open();
    cmd.ExecuteNonQuery();
    }
    

    But an exception rises (on the conn.Open() line) telling that :

    A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
    

    Which is very odd because I copied the exact connection string found in the Web.config file.

    How can I avoid this exception?

    PS: My goal is to get connected only programmatically to the database without the web.config file.

    Thank you,

    Regards.

  • Dany Gauthier
    Dany Gauthier over 8 years
    The url does not work anymore, I'm using Nuget to get the library, if not you can refer to system.data.sqlite.org
  • CodeMonkey
    CodeMonkey over 6 years
    Maybe it should be mentioned that this isn't merely a reference but a NuGet dependency.