文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

C#使用ADO.Net连接数据库与DbProviderFactory实现多数据库访问

2024-04-02 19:55

关注

一、ADO.Net数据库连接字符串

1、OdbcConnection(System.Data.Odbc)

(1)SQL Sever

标准安全:" Driver={SQL Server}; Server=Aron1; Database=pubs; Uid=sa; Pwd=asdasd; "

信任的连接:" Driver={SQL Server}; Server=Aron1; Database=pubs; Trusted_Connection=yes; "

(2)SQL Native Client ODBC Driver(>=SQL Server 2005)

标准安全" Driver={SQL Native Client}; Server=Aron1; Database=pubs; UID=sa; PWD=asdasd; "

信任的连接
" Driver={SQL Native Client}; Server=Aron1; Database=pubs; Trusted_Connection=yes; " --Integrated Security=SSPI 等同于Trusted_Connection=yes

(3)Oracle:

新版本:"Driver={Microsoft ODBC for Oracle}; Server=OracleServer.world; Uid=Username; Pwd=asdasd; "

旧版本:"Driver={Microsoft ODBC Driver for Oracle}; ConnectString=OracleServer.world; Uid=myUsername; Pwd=myPassword; "

(4)Access:

标准安全:"Driver={Microsoft Access Driver (*.mdb)}; Dbq=C:\mydatabase.mdb; Uid=Admin; Pwd=; "

2、OleDbConnection(System.Data.OleDb)

(1)SQL Sever

标准安全:" Provider=sqloledb; Data Source=Aron1; Initial Catalog=pubs; User Id=sa; Password=asdasd; "

信任的连接:
" Provider=sqloledb; Data Source=Aron1; Initial Catalog=pubs; Integrated Security=SSPI; " 
(use serverName\instanceName as Data Source to use an specifik SQLServer instance, only SQLServer2000)

(2)SQL Native Client OLE DB Provider(>=SQL Server 2005)

标准安全:" Provider=SQLNCLI; Server=Aron1; Database=pubs; UID=sa; PWD=asdasd; "

信任的连接:
" Provider=SQLNCLI; Server=Aron1; Database=pubs; Trusted_Connection=yes; " --Integrated Security=SSPI 等同于Trusted_Connection=yes

(3)Oracle:

标准安全:
"Provider=msdaora; Data Source=MyOracleDB; User Id=UserName; Password=asdasd; "
This one's from Microsoft, the following are from Oracle

标准安全:"Provider=OraOLEDB.Oracle; Data Source=MyOracleDB; User Id=Username; Password=asdasd; "

信任的连接:"Provider=OraOLEDB.Oracle; Data Source=MyOracleDB; OSAuthent=1; "

(4)Access:

标准安全:

"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=\somepath\mydb.mdb; User Id=admin; Password=; "

3、SqlConnection(Syste.Data.SqlClient) SQL专用

标准安全:

" Data Source=Aron1; Initial Catalog=pubs; User Id=sa; Password=asdasd; " 
- 或者 -" Server=Aron1; Database=pubs; User ID=sa; Password=asdasd; Trusted_Connection=False"

信任的连接:
" Data Source=Aron1; Initial Catalog=pubs; Integrated Security=SSPI; " 
- 或者 -
" Server=Aron1; Database=pubs; Trusted_Connection=True; " –(use serverName\instanceName as Data Source to use an specifik SQLServer instance, 仅仅适用于SQLServer2000)

4、OracleConnection(System.Data.OracleClient\Oracle.ManagedDataAccess.Client) Oracle专用

标准安全:
"Data Source=MyOracleDB; Integrated Security=yes; " --This one works only with Oracle 8i release 3 or later

指定用户名和密码:
"Data Source=MyOracleDB; User Id=username; Password=passwd; Integrated Security=no; "--This one works only with Oracle 8i release 3 or later

指定主机:
"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP) (HOST=192.168.115.33) (PORT=1521)))(CONNECT_DATA=(SERVICE_NAME= testDemo))); User Id=oracle_test; Password=oracle"
其中Oracle数据库服务器IP:192.168.115.33
ServiceName:testDemo
用户名:oracle_test
密码:oracle

二、利用DbProviderFactory创建各种ADO.Net对象

DbProviderFactory是一个工厂类,工厂类的作用提供其他一系列相互之间有关系的类。在这里,DbProviderFactory就自动生成了包括DbConnection、DbCommand、 DbDataAdapter等一系列数据库操作的相关类。

1、配置文件ConnectionString节:

<configuration> 
    <connectionStrings> 
        <add name="default"  connectionString="server=localhost; user id=sa; password=******; database=northwind" 
             providerName="System.Data.SqlClient"/>
    </connectionStrings> 
</configuration>

2、利用DbProviderFactory类自动查找数据库的驱动

ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["default"];
DbProviderFactory provider = DbProviderFactories.GetFactory(settings.ProviderName);

3、利用DbProviderFactory类实例创建各种ADO.Net对象。

using (DbConnection conn = provider.CreateConnection())
{
    conn.ConnectionString = settings.ConnectionString;
    conn.Open();
    DbCommand cmd = conn.CreateCommand();
    cmd.CommandText = "Select top 10 * From ShortTermBill";
    
    //使用DbDataAdapter
    DbDataAdapter da = provider.CreateDataAdapter();
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();
    da.Fill(ds);
    da.Dispose();
    Console.WriteLine(ds.Tables[0].Rows[0]["BillCode"]);
    
    //使用DbDataReader
    DbDataReader reader = cmd.ExecuteReader()
    while (reader.Read())
    {
        Console.WriteLine(reader.GetString(0));
    }
    conn.Close();
}

三、利用DbConnection获取数据库架构信息

SQL Server 架构集合 - ADO.NET | Microsoft 官方文档

class Program
{
    static void Main()
    {
        string connectionString = GetConnectionString();
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            // Connect to the database then retrieve the schema information.  
            connection.Open();string[] columnRestrictions = new String[4];

            // For the array, 0-member represents Catalog; 1-member represents Schema;
            // 2-member represents Table Name; 3-member represents Column Name.
            // Now we specify the Table_Name and Column_Name of the columns what we want to get schema information.
            columnRestrictions[2] = "Device";

            DataTable departmentIDSchemaTable = connection.GetSchema("Columns", columnRestrictions);

            ShowColumns(departmentIDSchemaTable);

        }
    }

    private static string GetConnectionString()
    {
        // To avoid storing the connection string in your code,  
        // you can retrieve it from a configuration file.  
        return "server=10.126.64.1;Database=TPM;user=it;pwd=;ApplicationIntent=ReadOnly;MultiSubnetFailover=True";
    }
    private static void ShowColumns(DataTable columnsTable)
    {
        var selectedRows = from info in columnsTable.AsEnumerable()
                           select new
                           {
                               TableCatalog = info["TABLE_CATALOG"],
                               TableSchema = info["TABLE_SCHEMA"],
                               TableName = info["TABLE_NAME"],
                               ColumnName = info["COLUMN_NAME"],
                               DataType = info["DATA_TYPE"],
                               ORDINAL_POSITION = info["ORDINAL_POSITION"],
                               COLUMN_DEFAULT = info["COLUMN_DEFAULT"],
                               IS_NULLABLE = info["IS_NULLABLE"],
                               CHARACTER_MAXIMUM_LENGTH = info["CHARACTER_MAXIMUM_LENGTH"],
                               NUMERIC_PRECISION = info["NUMERIC_PRECISION"],
                               NUMERIC_SCALE = info["NUMERIC_SCALE"],
                               DATETIME_PRECISION = info["DATETIME_PRECISION"],
                           };

        Console.WriteLine("{0,-15},{1,-15},{2,-15},{3,-15},{4,-15},{5,-15},{6,-15},{7,-15},{8,-15},{9,-15},{10,-15},{11,-15}", "TableCatalog", "TABLE_SCHEMA",
            "表名", "列名", "数据类型", "字段原始顺序", "列默认值", "是否可空", "字符串最大长度", "数字精度", "数字小数点位数", "日期精度"
            );
        foreach (var row in selectedRows)
        {
            Console.WriteLine("{0,-15},{1,-15},{2,-15},{3,-15},{4,-15},{5,-15},{6,-15},{7,-15},{8,-15},{9,-15},{10,-15},{11,-15}", row.TableCatalog,
                row.TableSchema, row.TableName, row.ColumnName, row.DataType, row.ORDINAL_POSITION, row.COLUMN_DEFAULT, row.IS_NULLABLE
                , row.CHARACTER_MAXIMUM_LENGTH, row.NUMERIC_PRECISION, row.NUMERIC_SCALE, row.DATETIME_PRECISION);
        }
    }
}

到此这篇关于C#使用ADO.Net连接数据库与DbProviderFactory实现多数据库访问的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯