一:C#串連SQL資料庫
DataSource=myServerAddress;Initial Catalog=myDataBase;UserId=myUsername;Password=myPassword;
DataSource=190.190.200.100,1433;Network Library=DBMSSOCN;InitialCatalog=myDataBase;User ID=myUsername;Password=myPassword;
Server=myServerAddress;Database=myDataBase;UserID=myUsername;Password=myPassword;
Trusted_Connection=False;
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Server=myServerNametheInstanceName;Database=myDataBase;Trusted_Connection=True;
DataSource=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;
1:Integrated Security參數
當設定Integrated Security為 True 的時候,串連語句前面的UserID, PW 是不起作用的,即採用windows身分識別驗證模式。
只有設定為 False 或省略該項的時候,才按照 UserID, PW 來串連。
IntegratedSecurity 還可以設定為:sspi,相當於True,建議用這個代替True.
DataSource=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;
DataSource=myServerAddress;Initial Catalog=myDataBase;Integrated Security=true;
DataSource=myServerAddress;Initial Catalog=myDataBase;;UserID=myUsername;
Password=myPasswordIntegrated Security=false;
2:參數Trusted_Connection
Trusted_Connection=true,將使用當前的 Windows 帳戶憑據進行身分識別驗證
Trusted_Connection=false;將不採用信任連接方式(也即不採用Windows驗證方式),而改由SQL Server 2000驗證方式
Server=myServerAddress;Database=myDataBase;UserID=myUsername;
Password=myPassword;Trusted_Connection=false;
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
3:Initial Catalog是你要串連的資料庫的名字
4:WINCE串連
DataSource=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;UserID=myDomainmyUsername;Password=myPassword;
二:可以利用SqlConnectionStringBuilder,這樣不必去記住名稱。
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
scsb.DataSource =@"(local)SQLExpress";
scsb.IntegratedSecurity = true;
scsb.InitialCatalog = "Northwind";
SqlConnectionmyConnection = new SqlConnection(scsb.ConnectionString);
三:可以利用屬性中的Setting來自動化佈建連接字串
1:在type中選擇(connection string),
2:在DataSouce中選擇資料來源,然後再Server中輸入伺服器名,本地用(local)SQLExpress
3:選擇登陸驗證方式,本次選Windows驗證(即信任連接IntegratedSecurity=True)
4:選擇資料庫名,確認即可
DataSource=(local)SQLExpress;Initial Catalog=Northwind;Integrated Security=True
server =.sqlexpress;integrated security = true;database = northwind
最後附上一個我自己的測試案例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace ConnectDB
{
class Program
{
static void Main(string[] args)
{
SqlConnection sqlCon = new SqlConnection();
sqlCon.ConnectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=SSPI";
sqlCon.Open();
SqlCommand sql_Command = new SqlCommand();
sql_Command.CommandText = "Query Text";
sql_Command.Connection = sqlCon;
SqlDataAdapter dbAdapter = new SqlDataAdapter(sql_Command);
DataSet dbSet = new DataSet();
dbAdapter.Fill(dbSet);
//dbSet.GetXml();
Console.WriteLine(dbSet.GetXml()。ToString());
sqlCon.Close();
Console.Read();
}
}
}