c# WinForm 读取SQLite数据库中信息

本文详细介绍如何在WinForm项目中使用SQLite数据库,包括NuGet包安装、配置App.config、解决平台兼容性问题及数据库连接代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考网址: https://www.cnblogs.com/nsky/p/4479850.html

1、新建WinForm项目,创建Button

2、右键解决方案资源管理器——管理NuGet程序包——搜索sqlite,下载System.Data.SQLite(x86/x64)——下载后AppConfig内容为——

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
    </providers>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SQLite.EF6" />
      <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
    <remove invariant="System.Data.SQLite" /><add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" /></DbProviderFactories>
  </system.data>
</configuration>

3、SQLite下载的平台类型不对,会造成报错:

未能加载文件或程序集“System.Data.SQLite, Version=1.0.66.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139”或它的某一个依赖项。试图加载格式不正确的程序。

所以需要右键解决方案资源管理器 中项目——属性——生成——平台目标——更改为x64

4、在App.config中添加连接数据库

<connectionStrings>
    <add name="sqlite" connectionString="Data Source=F:\SQLiteStudio\MyCustomDB.db\document.db;Pooling=true;FailIfMissing=false"
         providerName="System.Data.SQLite" />
  </connectionStrings>

5、WinForm中编写代码,查询数据库中数据信息

string sql = "SELECT * FROM 表名";
string connStr = @"Data Source=" + @"F:\SQLiteStudio\MyCustomDB.db;Initial Catalog=sqlite;Integrated Security=True;Max Pool Size=10";
    using (SQLiteConnection conn = new SQLiteConnection(connStr))
    {
        using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(sql, conn))
        {
            DataSet ds = new DataSet();
            adapter.Fill(ds);
    
            DataTable dt = ds.Tables[0];
            MessageBox.Show(dt.Columns[1].ColumnName, "数据库信息");
        }
    }

 

WinForms应用程序中连接SQLite数据库,可以使用System.Data.SQLite或Microsoft.Data.Sqlite等库。以下是一个基本的步骤和示例代码,展示如何在WinForms应用程序中连接SQLite数据库: 1. **安装SQLite库**: - 打开Visual Studio,打开你的WinForms项目。 - 在“解决方案资源管理器”中,右键点击项目名称,选择“管理NuGet程序包”。 - 搜索“System.Data.SQLite”或“Microsoft.Data.Sqlite”,然后安装它。 2. **添加引用**: - 安装完成后,库会自动添加到项目的引用中。 3. **编写连接代码**: - 在你的代码文件中,添加必要的using语句: ```csharp using System.Data.SQLite; using System.Windows.Forms; ``` 4. **示例代码**: ```csharp public partial class MainForm : Form { private SQLiteConnection connection; public MainForm() { InitializeComponent(); ConnectToDatabase(); } private void ConnectToDatabase() { string connectionString = "Data Source=mydatabase.db;Version=3;"; connection = new SQLiteConnection(connectionString); try { connection.Open(); MessageBox.Show("连接成功!"); } catch (Exception ex) { MessageBox.Show("连接失败: " + ex.Message); } } private void InsertData(string name, int age) { string query = "INSERT INTO users (name, age) VALUES (@name, @age)"; using (SQLiteCommand cmd = new SQLiteCommand(query, connection)) { cmd.Parameters.AddWithValue("@name", name); cmd.Parameters.AddWithValue("@age", age); cmd.ExecuteNonQuery(); } } private void SelectData() { string query = "SELECT * FROM users"; using (SQLiteCommand cmd = new SQLiteCommand(query, connection)) { using (SQLiteDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { string name = reader["name"].ToString(); int age = Convert.ToInt32(reader["age"]); MessageBox.Show("Name: " + name + ", Age: " + age); } } } } protected override void OnFormClosing(FormClosingEventArgs e) { if (connection != null && connection.State == System.Data.ConnectionState.Open) { connection.Close(); } base.OnFormClosing(e); } } ``` 这个示例代码展示了如何在WinForms应用程序中连接到SQLite数据库,执行插入和查询操作。请确保将“mydatabase.db”替换为你的数据库文件的实际路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值