C# WinForm連線SQL Server資料庫的不同方式
阿新 • • 發佈:2018-12-26
一、不同字串定義方式 1)直接定義字串並連線 `static SqlConnection conn;//定義連線物件 public static SqlConnection Connection//連線物件的屬性 { get { if (conn == null) { string connstr = "Data Source = (local); uid=sa;pwd=12345678;Initial Catalog =data_db; Integrated Security=SSPI";//本地連線 conn = new SqlConnection(connstr); conn.Open(); } else if (conn.State == ConnectionState.Closed) { conn.Open(); } else if (conn.State == ConnectionState.Broken) { conn.Close(); conn.Open(); } return conn; } }`
2)字串儲存在app.config檔案中定義
app.config檔案中新增:
資料庫連線類中引用:
public static string connstr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString; static SqlConnection conn; public static SqlConnection Connection//連線物件的屬性 { get { if (conn == null) { string connstr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString; conn = new SqlConnection(connstr); conn.Open(); } else if (conn.State == ConnectionState.Closed) { conn.Open(); } else if (conn.State == ConnectionState.Broken) { conn.Close(); conn.Open(); } return conn; }
二、連線字串各種情況下的定義
1)SQL身份驗證方式的本地資料庫連線
string strSqlConnect = “Data Source = (local); uid=sa;pwd=12345678;Initial Catalog =data_db; Integrated Security=SSPI”;
2)Windows身份驗證方式的本地資料庫連線
string strSqlConnect = “Data Source = (local); Initial Catalog =data_db; Integrated Security=SSPI”;
3)SQL身份驗證方式的遠端資料庫連線
string strSqlConnect = string.Format(@“server={0};uid=sa;pwd=12345678;database=data_db;Trusted_Connection=no”, ip + “,1433”);//使用IP遠端登入
其中:ip為伺服器IP地址,要確保你所使用的埠號在遠端伺服器上已經開放。