欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

整理两个PetaPoco连接SQLite数据库的方法

程序员文章站 2022-03-16 22:21:01
从https://github.com/qingask/PetaPoco.NetCore下载源文件压缩包 解压出文件PetaPoco.Multiple.cs、PetaPoco.NetCore.cs 放置System.Data.SQLite.dll文件到bin文件,这个需要从SQLite官方获取对应框... ......
  1. 从https://github.com/qingask/PetaPoco.NetCore下载源文件压缩包
  2. 解压出文件PetaPoco.Multiple.cs、PetaPoco.NetCore.cs
  3. 放置System.Data.SQLite.dll文件到bin文件,这个需要从SQLite官方获取对应框架集级对应位文件,应该可以直接通过NuGet获取。
  4. 方法1:
    1. 增加DbProviderFactories类,向PetaPoco注入SQLite实例
      public static class DbProviderFactories
      {
      
          internal static readonly Dictionary<string, DbProviderFactory> Configs = new Dictionary<string, DbProviderFactory>();
      
          static DbProviderFactories()
          {
              RegisterFactory("Microsoft.Data.Sqlite", SQLiteFactory.Instance);
          }
      
          public static DbProviderFactory GetFactory(string providerInvariantName)
          {
              if (Configs.ContainsKey(providerInvariantName))
              {
                  return Configs[providerInvariantName];
              }
              return null;
          }
      
          public static void RegisterFactory(string providerInvariantName, DbProviderFactory factory)
          {
              if (Configs.ContainsKey(providerInvariantName))
              {
                  Configs[providerInvariantName] = factory;
              }
              else
              {
                  Configs.Add(providerInvariantName, factory);
              }
          }
      
          public static IEnumerable<string> GetFactoryProviderNames()
          {
              return Configs.Keys.ToArray();
          }
      }

       

    2. 配置web.config
      <add name="PetaPocoConn" connectionString="Data Source=|DataDirectory|Demo.db"/>

       

    3. 链接语法 
      var db=new Database(new SQLiteConnection(ConfigurationManager.ConnectionStrings["PetaPocoConn"].ConnectionString));

       

  5.   方法2:
    1.   配置web.config 
       <system.data>
          <DbProviderFactories>
            <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>

       

    2. 链接字符串:
      <connectionStrings>
          <add name="PetaPocoConn" connectionString="Data Source=|DataDirectory|Demo.db" providerName="System.Data.SQLite" />
        </connectionStrings>

       

    3. 辅助类:
          public static class DbScoure
          {
              public static Database SqliteDataBase()
              {
                  var conn = ConfigurationManager.ConnectionStrings["PetaPocoConn"];
                  return new Database(conn.ConnectionString, conn.ProviderName);
              }
          }
      调用方式:
      var db=DbScoure.SqliteDataBase();