数据库连接字符串指定了访问数据源时所必须的信息,如口令、ID等。
在创建连接对象的时候,通常都将连接字符串直接传给连接对象的构造函数:
1 string conString = "Data Sourse =;Initial Catalog =;User Id = ;Password = "; 2 OleDbConnection DataOleDbConnection = new OleDbConnection(conString); 3 DataOleDbConnection.Open();
也可以采用一种更加安全、面向对象的方式建立字符串,即使用托管数据提供的ConnectionStringBuilder类,代码如下:
1 SqlConnectionStringBuilder sqlCSB = new SqlConnectionStringBuilder(); 2 sqlCSB.DataSource = "MYSERVER"; 3 sqlCSB.Password = ""; 4 sqlCSB.UserID = ""; 5 sqlCSB.InitialCatalog = ""; 6 SqlConnection conn = new SqlConnection(sqlCSB.ConnectionString); 7 conn.Open();