Nikalas1111
Nikalas1111

Reputation: 61

How to connect C# app with SQLite database

I want to connect to a SQLite database. Please show me example code which WORKS. Also I want to link datagridview with the database.I use this code but it doesn't work:

private DataTable dt;
public Form1()
{
    InitializeComponent();
    this.dt = new DataTable();
}
private SQLiteConnection SQLiteConnection;
private void DataClass()
{
    SQLiteConnection = new SQLiteConnection("Data Source=PasswordManager.s3db;Version=3;");
}
private void GetData()
{
    SQLiteDataAdapter DataAdapter;
    try
    {
    SQLiteCommand cmd;
    SQLiteConnection.Open();  //Initiate connection to the db
    cmd = SQLiteConnection.CreateCommand();
    cmd.CommandText = "select*from PasswordManager;";  //set the passed query
    DataAdapter = new SQLiteDataAdapter(cmd);
    DataAdapter.Fill(dt); //fill the datasource
    dataGridView1.DataSource = dt;
}
catch(SQLiteException ex)
{
    //Add your exception code here.
}
SQLiteConnection.Close();

Upvotes: 1

Views: 10554

Answers (2)

DRapp
DRapp

Reputation: 48179

In addition to the answer provided by Darin, there is no "create database" command in SQLite (from what I remember). When you initiate a "SQLiteConnection", if the given database (.db3) does not exist, it automatically creates it... from there, you can then create your tables.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

You could use the System.Data.SQLite ADO.NET provider. Once you download and reference the assembly, it's pretty straightforward ADO.NET code:

using (var conn = new SQLiteConnection(@"Data Source=test.db3"))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT id FROM foo";
    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            int id = reader.GetInt32(reader.GetOrdinal("id"));
            ...
        }
    }
}

Upvotes: 4

Related Questions