标签:
我们知道连接数据库的方式有两种,一种是windows验证,一种是server验证,区别在于一个本地不需要账号和密码,一个可本地可远程需要账号密码。
而使用ado.net连接到数据库是通过连接字符串来连接的,两种方式的操作分别如下:
//本地连接方法 SqlConnectionStringBuilder connStrBuilder = new SqlConnectionStringBuilder(); connStrBuilder.DataSource = "databasename\\SQLEXPRESS";//or @"databasename\SQLEXPRESS" connStrBuilder.InitialCatalog = "StudyUse"; connStrBuilder.IntegratedSecurity = true; SqlConnection conn = new SqlConnection(); conn.ConnectionString = connStrBuilder.ConnectionString; try { conn.Open(); //操作数据库 } catch(Exception) { switch(conn.State) { //做一些错误处理 default: break; } throw; } finally { //释放 conn.Close(); }
SqlConnectionStringBuilder类相当于一个辅助类,可以以对象的方式操作连接字符串,当然,我们也可以直接填写连接字符串,如:
SqlConnection conn = new SqlConnection(); conn.ConnectionString = @"Data Source=databasename\SQLEXPRESS;Initial Catalog=StudyUse;Integrated Security=True";
使用sqlserver连接的话,则需要输入用户名和密码以及设置InitialCatalog为false(默认为false):
//Sql连接方法 SqlConnectionStringBuilder connStrBuilder = new SqlConnectionStringBuilder(); connStrBuilder.DataSource = "databasename\\SQLEXPRESS";//or @"databasename\SQLEXPRESS" connStrBuilder.InitialCatalog = "StudyUse"; connStrBuilder.UserID = "User ID"; connStrBuilder.Password = "Password"; SqlConnection conn = new SqlConnection(); conn.ConnectionString = connStrBuilder.ConnectionString;
标签:
原文地址:http://www.cnblogs.com/blackerXHunter/p/4540476.html