一: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();
}
}
}