溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C#怎么使用ADO.Net連接數(shù)據(jù)庫(kù)與實(shí)現(xiàn)多數(shù)據(jù)庫(kù)訪問(wèn)

發(fā)布時(shí)間:2022-05-12 10:52:36 來(lái)源:億速云 閱讀:507 作者:iii 欄目:開(kāi)發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“C#怎么使用ADO.Net連接數(shù)據(jù)庫(kù)與實(shí)現(xiàn)多數(shù)據(jù)庫(kù)訪問(wèn)”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“C#怎么使用ADO.Net連接數(shù)據(jù)庫(kù)與實(shí)現(xiàn)多數(shù)據(jù)庫(kù)訪問(wèn)”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來(lái)學(xué)習(xí)新知識(shí)吧。

一、ADO.Net數(shù)據(jù)庫(kù)連接字符串

1、OdbcConnection(System.Data.Odbc)

(1)SQL Sever

標(biāo)準(zhǔn)安全:" 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)

標(biāo)準(zhǔn)安全" 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:

標(biāo)準(zhǔn)安全:"Driver={Microsoft Access Driver (*.mdb)}; Dbq=C:\mydatabase.mdb; Uid=Admin; Pwd=; "

2、OleDbConnection(System.Data.OleDb)

(1)SQL Sever

標(biāo)準(zhǔn)安全:" 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)

標(biāo)準(zhǔn)安全:" 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:

標(biāo)準(zhǔn)安全:
"Provider=msdaora; Data Source=MyOracleDB; User Id=UserName; Password=asdasd; "
This one's from Microsoft, the following are from Oracle

標(biāo)準(zhǔn)安全:"Provider=OraOLEDB.Oracle; Data Source=MyOracleDB; User Id=Username; Password=asdasd; "

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

(4)Access:

標(biāo)準(zhǔn)安全:

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

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

標(biāo)準(zhǔn)安全:

" 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專用

標(biāo)準(zhǔn)安全:
"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

指定主機(jī):
"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數(shù)據(jù)庫(kù)服務(wù)器IP:192.168.115.33
ServiceName:testDemo
用戶名:oracle_test
密碼:oracle

二、利用DbProviderFactory創(chuàng)建各種ADO.Net對(duì)象

DbProviderFactory是一個(gè)工廠類,工廠類的作用提供其他一系列相互之間有關(guān)系的類。在這里,DbProviderFactory就自動(dòng)生成了包括DbConnection、DbCommand、 DbDataAdapter等一系列數(shù)據(jù)庫(kù)操作的相關(guān)類。

1、配置文件ConnectionString節(jié):

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

2、利用DbProviderFactory類自動(dòng)查找數(shù)據(jù)庫(kù)的驅(qū)動(dòng)

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

3、利用DbProviderFactory類實(shí)例創(chuàng)建各種ADO.Net對(duì)象。

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獲取數(shù)據(jù)庫(kù)架構(gòu)信息

SQL Server 架構(gòu)集合 - 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",
            "表名", "列名", "數(shù)據(jù)類型", "字段原始順序", "列默認(rèn)值", "是否可空", "字符串最大長(zhǎng)度", "數(shù)字精度", "數(shù)字小數(shù)點(diǎn)位數(shù)", "日期精度"
            );
        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連接數(shù)據(jù)庫(kù)與實(shí)現(xiàn)多數(shù)據(jù)庫(kù)訪問(wèn)”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過(guò)才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI