Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access SQLite with C#?

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.

like image 755
Zakaria Avatar asked Sep 15 '10 14:09

Zakaria


People also ask

Is SQLite written in C?

SQLite is written in ANSI-C. The C programming language is used because it is the universal assembly language - it can run on just about any hardware and on just about any operating system. No matter what programming language is used for the application code, it can usually interface easily with a library written in C.

How do I access sqlite3 from command line?

Start the sqlite3 program by typing "sqlite3" at the command prompt, optionally followed by the name of the file that holds the SQLite database (or ZIP archive). If the named file does not exist, a new database file with the given name will be created automatically.

How do I access SQLite memory?

The most common way to force an SQLite database to exist purely in memory is to open the database using the special filename ":memory:". In other words, instead of passing the name of a real disk file into one of the sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2() functions, pass in the string ":memory:".


2 Answers

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())
  {
    //...
  }
}
like image 187
Rudu Avatar answered Nov 01 '22 21:11

Rudu


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

like image 21
Alex Reitbort Avatar answered Nov 01 '22 23:11

Alex Reitbort