參考文獻:
前言:
之前寫過一篇博客:Sql Server的JDBC測試程序與遠程連接,現在來講講在.net 平台下如何連接sql server數據庫。有多種方式可以連接數據庫,分別是ODBC,OLEDB,ADO,ADO.NET。每一種連接所使用的驅動程序以及連接字符串都不相同,具體如何寫數據庫連接字符串可以參考這個網站http://www.connectionstrings.com/。上面列出了大多數數據源的數據庫連接字符串。
ADO.NET
首先我們將如何使用ado.net來連接數據庫,這也是使用最頻繁的方法了。參考程序如下:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace SQLServerConnection { class Program { static void Main(string[] args) { //默認實例 //string connectionString = "Data Source=SERVER_NAME;Initial Catalog=AdventureWorks2008R2;User ID=sa;Password=sa12345"; //命名實例 string connectionString = "Data Source=SERVER_NAME\\SQL2012;Initial Catalog=AdventureWorks2012;User Id=sa;Password=sa12345"; // Assumes connectionString is a valid connection string. using (SqlConnection connection = new SqlConnection(connectionString)) { //打開連接 connection.Open(); // Do work here. SqlCommand sqlcmd = connection.CreateCommand(); //sqlcmd.CommandText = "select top 10 * from Person.Person;"; sqlcmd.CommandText = "select top 10 * from Person;"; SqlDataReader sqlreader = sqlcmd.ExecuteReader(); while (sqlreader.Read()) { Console.WriteLine("\t{0}\t{1}",sqlreader["firstname"],sqlreader["lastname"]); } sqlreader.Close(); connection.Close();//因為使用了using,所以這一條語句可以不寫,因為當離開using代碼塊以后,connection自動關閉 } } } }
常見的SQLClient連接字符串有:

Integrated Security=Yes;Data Source=MyServer; Initial Catalog=MyDatabase; Data Source=ServerName ;User ID=UserName;Password=UserPassword; Data Source=ServerName\InstanceName;Integrated Security=Yes
之所以說是使用ADO.NET是因為使用了SqlConnection這個連接類
OLEDB

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.OleDb; namespace OleConnection { class Program { static void Main(string[] args) { string connectionString = "Provider=SQLOLEDB;Data Source=T-WEIXU-W7\\SQL2012;Initial Catalog=AdventureWorks2012;Integrated Security=SSPI;"; // Assumes connectionString is a valid connection string. using (OleDbConnection connection = new OleDbConnection(connectionString)) { //打開連接 connection.Open(); // Do work here. OleDbCommand sqlcmd = connection.CreateCommand(); sqlcmd.CommandText = "select top 10 * from Person.Person;"; //sqlcmd.CommandText = "select top 10 * from Person;"; OleDbDataReader sqlreader = sqlcmd.ExecuteReader(); while (sqlreader.Read()) { Console.WriteLine("\t{0}\t{1}", sqlreader["firstname"], sqlreader["lastname"]); } sqlreader.Close(); connection.Close(); } } } }
下面是常見的OLEDB連接字符串:

Provider=SQLOLEDB;Data Source=ServerName;Integrated Security=SSPI; Provider=SQLOLEDB;Data Source=ServerName;User Id=UserName;Pasword=UserPassword; Provider=SQLOLEDB;Data Source=ServerName\InstanceName;Integrated Security=SSPI; Provider=SQLNCLI11;Data Source=ServerName\InstanceName;Integrated Security=SSPI;
打開D:\Program Files (x86)\Microsoft Data Access SDK 2.8\Tools\x86\RowsetViewer.exe中可以查看本機的oledb驅動程序。我的機器上就有比如
- SQLOLEDB
- SQLNCLI10
- SQLNCLI11
這樣的三類oledb驅動程序,