【问题标题】:How to connect C# app with SQLite database如何将 C# 应用程序与 SQLite 数据库连接起来
【发布时间】:2012-02-10 19:24:37
【问题描述】:

我想连接到 SQLite 数据库。请向我展示可行的示例代码。我还想将datagridview与数据库链接。我使用此代码但它不起作用:

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

【问题讨论】:

标签: c# winforms sqlite connection


【解决方案1】:

您可以使用System.Data.SQLite ADO.NET 提供程序。下载并引用程序集后,它就是非常简单的 ADO.NET 代码:

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】:

除了 Darin 提供的答案之外,SQLite 中没有“创建数据库”命令(据我记忆)。当您启动“SQLiteConnection”时,如果给定的数据库 (.db3) 不存在,它会自动创建它...然后您可以从那里创建表。

【讨论】:

  • 我知道怎么做,所以对我来说没问题
  • @Nikalas1111,没问题,但是对于可能是 SQLite 新手并且不了解引擎和创建连接的其他人可以帮助他们解决我认为不是的缺失部分当我最初开始使用它时,有据可查:)
猜你喜欢
  • 1970-01-01
  • 2022-06-14
  • 2016-03-21
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
  • 2013-05-12
相关资源
最近更新 更多