引言
经过使用一段时间后对FastReport
的多数据源产生了兴趣,主要是想看下如何对数据库默认的对象进行获取的,以前自行做多数据库的处理都是根据自己写Sql
进行操作,突然之间发现了内部使用的GetSchema()
方法,当时有点懵,还是说明自己对Ado.Net不够深入。
UML类结构
测试代码
在测试的时候使用了roslynpad工具进行测试,其实还有另外一款工具LinqPad。
代码片长,可以针对性的进行查看,也可以查看github。
#r "nuget:Npgsql/3.2.7"
#r "nuget:MySql.Data/6.10.7"
#r "nuget:MongoDB.Driver/2.5.0"
// Framwork
#r "nuget:Oracle.ManagedDataAccess/19.11.0"
// Net Core
#r "nuget:Microsoft.Data.SqlClient/2.1.2"
#r "nuget:Oracle.ManagedDataAccess.Core/2.12.0-beta3"
// <.net core 3.1使用
using System.Data.SqlClient;
// >.net core 3.1使用
using Microsoft.Data.SqlClient;
using MySql.Data.MySqlClient;
using Oracle.ManagedDataAccess.Client;
using Npgsql;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using MongoDB.Bson;
#region 连接字符串测试
DataConnectionBase ms = new MsSqlDataConnection();
var str1 = ms.GetConnectionStringWithLoginInfo("sa", "123");
ms.ConnectionString = str1;
str1.Dump("MsSqlDataConnection");
DataConnectionBase mysql = new MySqlDataConnection();
var str2 = mysql.GetConnectionStringWithLoginInfo("root", "123456");
mysql.ConnectionString = str2;
str2.Dump("MySqlDataConnection");
DataConnectionBase oracle = new OracleDataConnection();
var str3 = oracle.GetConnectionStringWithLoginInfo("cy", "123");
oracle.ConnectionString = str3;
str3.Dump("OracleDataConnection");
DataConnectionBase pgsql = new PostgresDataConnection();
var str4 = pgsql.GetConnectionStringWithLoginInfo("sa", "123");
pgsql.ConnectionString = str4;
str4.Dump("PostgresDataConnection");
DataConnectionBase mg = new MongoDBDataConnection();
var str5 = mg.GetConnectionStringWithLoginInfo("root", "123456");
mg.ConnectionString = str5;
str5.Dump("MongoDBDataConnection");
#endregion
#region 获取数据库对象测试
ms.GetTableNames().Dump("SqlServer TableNames");
mysql.GetTableNames().Dump("MySql TableNames");
oracle.GetTableNames().Dump("Oracle TableNames");
mg.GetTableNames().Dump("MongoDb TableNames");
pgsql.GetTableNames().Dump("PostGreSql TableNames");
#endregion
public abstract partial class DataConnectionBase
{
public abstract string ConnectionString
{
get;
set;
}
public abstract string GetConnectionStringWithLoginInfo(string userName, string password);
public DbConnection GetConnection()
{
Type connectionType = GetConnectionType();
if (connectionType != null)
{
DbConnection connection = GetDefaultConnection();
if (connection != null)
return connection;
// create a new connection object
connection = Activator.CreateInstance(connectionType) as DbConnection;
connection.ConnectionString = ConnectionString;
return connection;
}
return null;
}
private DbConnection GetDefaultConnection()
{
return null;
}