SQL Server基礎(七) VS2015 連線資料庫——基礎入門篇:主要分為配置並載入App.config檔案、建立資料工廠物件、建立連線物件、建立命令物件、建立讀取器物件幾個步驟。
阿新 • • 發佈:2019-01-09
一、簡介
1、關於學習C#如何連線資料庫或斷開連線資料(斷開連線資料庫往後我將討論),我是按照這本書一點一點學習的。
現在,終於用到了資料庫,於是,學習如何去連線資料庫。我們主要討論21.7/21.8/21.9小結,其他部分用到的話,我會重點闡述:
2、 好了,關於如何建立資料庫,我在21.6小結中已經建立了Autolot資料庫。這裡不過多地討論如何建立資料庫及資料表。詳情請參考連結:
https://blog.csdn.net/xpj8888/article/details/85985592
3、那麼最後,我們將逐步地展開。如圖所示,我細分為下面幾個步驟。
二、配置App.config檔案
資料庫的連線,不是非得配置App.config檔案。你也可以直接在Main函式裡面直接連線。App.config檔案的好處是它的靈活性。
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /> </startup> <!--方法1:直接在appSettings節點內定了伺服器和資料庫的連線--> <appSettings> <!--連線SQLServer資料庫--> <add key="provider" value="System.Data.SqlClient"/> <!--(localdb)\MSSQLLocalDB 表示本地伺服器--> <!--E:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL14.MSSQLSERVER\MSSQL\DATA\MYSQL_LIBRARY\AUTOLOT.MDF 表示表示載入的資料庫--> <add key="cnStr" value="Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = E:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL14.MSSQLSERVER\MSSQL\DATA\MYSQL_LIBRARY\AUTOLOT.MDF; Integrated Security = True"/> </appSettings> <!--方法2:在appSettings節點內定了伺服器的連線、在connectionStrings定義資料庫的連線。該方法的好處是,你可以動態連線需要連線的資料庫--> <connectionStrings> <add name="AutoLotSqlProvider" connectionString="Data Source = (localdb)\MSSQLLocalDB; Integrated Security = SSPI; Initial Catalog = E:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL14.MSSQLSERVER\MSSQL\DATA\MYSQL_LIBRARY\AUTOLOT.MDF"/> <add name="AutoLotOleDbProvider" connectionString="Data Source = (localdb)\MSSQLLocalDB; Integrated Security = SSPI; Initial Catalog = E:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL14.MSSQLSERVER\MSSQL\DATA\MYSQL_LIBRARY\AUTOLOT.MDF"/> </connectionStrings> </configuration>
使用配置檔案配置資料庫的好處是,你可以隨意切換連線哪種型別資料,比如連線"System.Data.OleDb資料,那麼你只需要更改下面的一行程式碼即可:
<add key="provider" value="System.Data.OleDb"/>
三、載入App.config檔案
#region *******步驟1:載入配置檔案******* //資料提供者:實際上就是要連線SQLServer資料庫 string strDataProvider = ConfigurationManager.AppSettings["provider"]; //連線SQLServer資料庫的名字 string strConnectStr = ConfigurationManager.AppSettings["cnStr"]; #endregion
四、建立資料提供搬運工廠的物件
#region *******步驟2:建立資料提供搬運工廠的物件*******
//資料搬運的中介,將資料庫的資料搬運到C#主程式,所以它有一個專業的名字叫:資料提供程式工廠
DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory(strDataProvider);
#endregion
五、建立連線物件並配置連線物件、開啟連線物件
#region *******步驟3:連線物件*******
//建立連線物件
using (DbConnection dbConnection = dbProviderFactory.CreateConnection())
{
//配置連線物件
dbConnection.ConnectionString = strConnectStr;
//開啟連線物件
dbConnection.Open();
#endregion
}
六、建立命令物件並配置命令物件
#region *******步驟4:命令物件*******
//建立命令物件
DbCommand dbCommand = dbProviderFactory.CreateCommand();
Console.WriteLine("dbCommand.GetType().Name = ", dbCommand.GetType().Name);
//配置命令物件
dbCommand.Connection = dbConnection; //命令物件需要連線的實體。
dbCommand.CommandText = "Select * From Inventory"; //命令物件執行的文字指令(即SQL語句)
#endregion
七、建立資料讀取器物件,並輸出本地伺服器的資料庫的資料表Inventory的內容
#region *******步驟5:資料讀取器物件*******
//建立資料讀取器物件
using (DbDataReader dbDataReader = dbCommand.ExecuteReader())
{
Console.WriteLine("dbDataReader.GetType().Name = ", dbDataReader.GetType().Name);
while (dbDataReader.Read())
{
Console.WriteLine("輸出當前汽車資料表Inventory的汽車ID及其品牌");
Console.WriteLine("CarID = {0}, Make = {1}", dbDataReader["CarID"],
dbDataReader["Make"].ToString());
}
}
#endregion
附錄:附上C#控制檯的所有程式碼及輸出結果
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<!--連線SQLServer資料庫-->
<add key="provider" value="System.Data.SqlClient"/>
<!--(localdb)\MSSQLLocalDB 表示本地伺服器-->
<!--E:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL14.MSSQLSERVER\MSSQL\DATA\MYSQL_LIBRARY\AUTOLOT.MDF 表示表示載入的資料庫-->
<add key="cnStr" value="Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = E:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL14.MSSQLSERVER\MSSQL\DATA\MYSQL_LIBRARY\AUTOLOT.MDF; Integrated Security = True"/>
</appSettings>
</configuration>
Program.cs:
#region 連線資料庫
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Configuration; //ConfigurationManager類的名稱空間
//using System.Data;
//using System.Data.SqlClient;
using System.Data.Common; //DbProviderFactory、DbProviderFactories、DbConnection、DbCommand、DbDataReader的名稱空間
namespace test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("重要的事情說三遍:我要準備開始連線資料了,各位。然後列印一張資料表到控制檯給大家look look ");
Console.WriteLine("重要的事情說三遍:我要準備開始連線資料了,各位。然後列印一張資料表到控制檯給大家look look ");
Console.WriteLine("重要的事情說三遍:我要準備開始連線資料了,各位。然後列印一張資料表到控制檯給大家look look ");
#region *******步驟1:載入配置檔案*******
//資料提供者:實際上就是要連線SQLServer資料庫
string strDataProvider = ConfigurationManager.AppSettings["provider"];
/*連線SQLServer資料庫的名字*/
//方法1:連線App.config的appSettring節點
string strConnectStr = ConfigurationManager.AppSettings["cnStr"];
//方法2:連線App.config的ConnectionStrings節點的資料庫
string strConnectStr2 = ConfigurationManager.ConnectionStrings["AutoLotSqlProvider"].ConnectionString;
#endregion
#region *******步驟2:建立資料提供搬運工廠的物件*******
//資料搬運的中介,將資料庫的資料搬運到C#主程式,所以它有一個專業的名字叫:資料提供程式工廠
DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory(strDataProvider);
#endregion
#region *******步驟3:連線物件*******
//建立連線物件
using (DbConnection dbConnection = dbProviderFactory.CreateConnection())
{
//配置連線物件
dbConnection.ConnectionString = strConnectStr;//方法2:strConnectStr2
//開啟連線物件
dbConnection.Open();
#endregion
#region *******步驟4:命令物件*******
//建立命令物件
DbCommand dbCommand = dbProviderFactory.CreateCommand();
Console.WriteLine("dbCommand.GetType().Name = " + dbCommand.GetType().Name);
//配置命令物件
dbCommand.Connection = dbConnection; //命令物件需要連線的實體。
dbCommand.CommandText = "Select * From Inventory"; //命令物件執行的文字指令(即SQL語句)
#endregion
#region *******步驟5:資料讀取器物件*******
//建立資料讀取器物件
using (DbDataReader dbDataReader = dbCommand.ExecuteReader())
{
Console.WriteLine("dbDataReader.GetType().Name = " + dbDataReader.GetType().Name);
while (dbDataReader.Read())
{
//Console.WriteLine("輸出當前汽車資料表Inventory的汽車ID及其品牌");
Console.WriteLine("CarID = {0}, Make = {1}", dbDataReader["CarID"], dbDataReader["Make"].ToString());
}
}
#endregion
}
Console.ReadLine();
}
}
}
#endregion
輸出結果: