所以,我正在做一个做很多事情的网站,其中之一是做一个动态连接字符串...我已经做过,但是因为我从互联网上获取了代码,所以我有点迷路了,所以我希望有人能帮忙解释一下它的工作原理以及每件事的作用...
代码如下:
protected void Page_Load(object sender, EventArgs e)
{
AddUpdateConnectionString("ConString");
}
void AddUpdateConnectionString(string name)
{
bool isNew = false;
string path = Server.MapPath("~/Web.Config");
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[@name='{0}']", name));
XmlNode node;
isNew = list.Count == 0;
if (isNew)
{
node = doc.CreateNode(XmlNodeType.Element, "add", null);
XmlAttribute attribute = doc.CreateAttribute("name");
attribute.Value = name;
node.Attributes.Append(attribute);
attribute = doc.CreateAttribute("connectionString");
attribute.Value = "";
node.Attributes.Append(attribute);
attribute = doc.CreateAttribute("providerName");
attribute.Value = "System.Data.SqlClient";
node.Attributes.Append(attribute);
}
else
{
node = list[0];
}
string conString = node.Attributes["connectionString"].Value;
SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(conString);
conStringBuilder.InitialCatalog = TxtBaseDeDados.Text;
conStringBuilder.DataSource = TxtHost.Text;
conStringBuilder.IntegratedSecurity = false;
conStringBuilder.UserID = TxtUtilizador.Text;
conStringBuilder.Password = TxtPalavraPasse.Text;
node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString;
if (isNew)
{
doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node);
}
doc.Save(path);
}
protected void Button1_Click(object sender, EventArgs e)
{
AddUpdateConnectionString("ConString");
}
答案 0 :(得分:-1)
如果要从web.config文件中加载连接字符串,我建议您使用ConfigurationManager类,如下所示:
<Dropdown
text='File'
fluid
>
<Dropdown.Menu >
<Dropdown.Item text='Add section'
onClick={this.addSection}
/>
<Dropdown.Divider />
<Dropdown.Item text='New lesson' />
<Dropdown.Item text='Open lesson' description='ctrl + o' />
<Dropdown.Item text='Save lesson' description='ctrl + s'
onClick={this.handleSave}
/>
<Dropdown.Divider />
<Dropdown.Item text='Delete lesson' description='ctrl + d' />
</Dropdown.Menu>
</Dropdown>
WingtipToys会像这样存储在web.config中
ConfigurationManager.ConnectionStrings["WingtipToys"].ConnectionString
答案 1 :(得分:-1)
它将在web.config文件中创建或更新设置,该设置用于存储有关如何连接到后端数据库的详细信息。配置文件是XML文档(以分层格式排列),因此代码可以找到配置,在配置内部找到合适的部分(如果不存在则创建它),构造一个新的连接字符串,并将其存储在XML中并保存更改。