How to connect C# app with SQLite database

自古美人都是妖i 提交于 2019-12-08 07:37:54

问题


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();

回答1:


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"));
            ...
        }
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/8870092/how-to-connect-c-sharp-app-with-sqlite-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!