c# WinForm 讀取SQLite數據庫中信息

參考網址: 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, "數據庫信息");
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章