返回不同数据库类型的IDBConnection

根据项目需求,可能需要使用不同数据库类型,比如MySql,Sql server,Pgsql等,那么需要实现不同的数据库连接类IDbConnection

代码如下:

public static IDbConnection GetConnection(string connString = null)
        {
            if (connString == null) { connString = ConnectionPool[DefaultConnName]; }
            if (DBType.Name == DbCurrentType.MySql.ToString())
            {
                return new MySql.Data.MySqlClient.MySqlConnection(connString);
            }
            if (DBType.Name == DbCurrentType.PgSql.ToString())
            {
                return new NpgsqlConnection(connString);
            }
            return new SqlConnection(connString);
        }

其中DBType是我们在配置中设置的数据库类型,它是静态常量,DBCuurrentType是数据库名的枚举类型

DBType全局赋值方法(从配置对象中读取)

_connection = provider.GetRequiredService<IOptions<Connection>>().Value;

DBType.Name = _connection.DBType;

使用Mysql需要引用包:Pomelo.EntityFrameworkCore.MySql

使用Pgsql需要引用包:Npgsql

使用Sql Server需要引用:System.Data.SqlClient

记录编程的点滴,体会学习的乐趣
原文地址:https://www.cnblogs.com/AduBlog/p/13658858.html