config数据库字符串:
<connectionStrings>
<add name="MyWebDataString" connectionString="server=192.168.0.4;database=CLWMSDB;uid=sa;pwd=******" />
</connectionStrings>
读取字符串(2种方法):
(1)添加System.Web引用
string connctionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["connectionString"].ToString();
(2)添加System.Configuration引用
string connctionString = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ToString();
读取单个项:
SqlConnection con =new SqlConnection(connctionString);
con.Open();
string aserver=con.DataSource;//读取服务器 192.168.0.4
string asql = con.Database;//读取数据库 CLWMSDB
说明:
(1)上面这种方法不知道为什么只可以读取服务器地址和数据库,不可用读取用户名和密码。
(2)读取用户名和密码的方法如下(很笨的方法,即分割字符串):
string[] constr = connctionString.Split(';');
string[] strUser = constr[2].Split('=');
string UserId = strUser[1].Trim(); //用户名
// 密码 strPassword[1].Trim()
string[] strPassword = constr[3].Split('=');
txtPassword.TextMode = TextBoxMode.Password;
this.txtPassword.Attributes.Add("value", strPassword[1].Trim());
说明一下:如果窗体是以密码框的方式,最好加上this.txtPassword.Attributes.Add("value", strPassword[1].Trim()); 否则不显示密码;
修改字符串:
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConnectionStringsSection conSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
//修改后的字符串
string newstr = "server=" + txtServer.Text.Trim() + ";database=" + txtSql.Text.Trim() + ";uid=" + txtUser.Text.Trim() + ";pwd=" + txtPassword.Text.Trim();
conSection.ConnectionStrings["MyWebDataString"].ConnectionString = newstr;
config.Save();
SqlConnection conn= new SqlConnection(newstr);
//验证是否联通数据库
if (con.State != ConnectionState.Open) {
try {
con.Open();
} catch {
ScriptManager.RegisterStartupScript(this, GetType(), "aa", "alert('保存成功!但是配置无效!')", true);
return;
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。