正常情况下写的连接字符串:
connStr = "Data Source=127.0.0.1;DataBase=Hydor;UID=***;PWD=***;Pooling=true;Min Pool Size=1;Max Pool Size=20;";
有时我们还要用参数拼连接字符串:
connStr = "Data Source=" + myDataSource + ";DataBase=" + myDataBase + ";UID="
+ userID + ";PWD=" + dbPassword + ";Pooling=true;Min Pool Size=1;Max Pool Size=20;";
参数一多,写起来和看上去就都没那么happy了~ 用SqlConnectionStringBuilder就会看上去清爽一些~
下面是它的写法,和一些常用属性。
var connStrBuilder = new SqlConnectionStringBuilder();
connStrBuilder.DataSource = myDataSource ; //IP
connStrBuilder.InitialCatalog = "Hydor"; //数据库名
connStrBuilder.UserID = userID; //数据库身份验证ID
connStrBuilder.Password = dbPassword; //密码
connStrBuilder.Pooling=true; //是否汇入连接池
connStrBuilder.MinPoolSize = 1; //最小连接池连接数
connStrBuilder.MaxPoolSize = 20; //最大连接数
connStrBuilder.IntegratedSecurity = false; //false:用户名密码验证 true:windows身份验证
connStrBuilder.MultipleActiveResultSets = true; //是否允许保留多活动结果集 (MARS)
SqlConnection sqlcon = new SqlConnection();
sqlcon.ConnectionString = connStrBuilder.ConnectionString;
//转成连接字符串
sqlcon.Open();
向已有连接字符串提供数据:
connStr = "Data Source=127.0.0.1;DataBase=Hydor;UID=***;PWD=***;"; var connStrBuilder = new SqlConnectionStringBuilder(connStr); //connStr是已有的连接字符串,向其添加连接池设置 connStrBuilder.Pooling=true; connStrBuilder.MinPoolSize = 1; connStrBuilder.MaxPoolSize = 20;
其他写法:
以password属性为例,下面俩种写法是完全一样的~
connStrBuilder["password"] = "***";
connStrBuilder.Password = "***";
优点:
方便创建和管理连接字符串,节省字符串拼接的性能消耗(这个应该性能影响微乎其微 )。
用 SqlConnectionStringBuilder 来写连接字符串,向连接字符串添加设置,布布扣,bubuko.com