![](/img/trans.png)
[英]In C# , how can I read a connection string stored in my web.config file connection string?
[英]How do I write an external connection string config file and make my c# application recognize and read it?
我当前的c#Windows窗体应用程序正在使用以下代码连接到数据库以检索信息,并将其存储在Setting.cs中
public static String connectionString ="Data Source=####; Initial Catalog=###; User ID=####; Password='####'";
我已经写了一个外部Connection.config文件,其内容为:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Connection" providerName="System.Data.providername"
connectionString="Data Source=####; Initial Catalog=###; User ID=###; Password='####!';" />
</connectionStrings>
</configuration>
上面的代码编写正确吗? 因为我只是在线复制和粘贴并编辑了连接字符串部分,因为我不知道“添加名称”和providerName部分的作用。
我想问的是,我应该在哪里在窗体中编写代码以从外部配置文件中读取连接字符串,以便可以在我的setting.cs文件中删除该代码。
谢谢。
不要介意###,因为它只是由我代替以表示信息。
您可以使用配置源拆分配置文件。 示例App / web.config:
<connectionStrings configSource="myExternalConfigSource.xml" />
外部配置:
<connectionStrings>
<add name="Connection" providerName="System.Data.providername"
connectionString="Data Source=####; Initial Catalog=###; User ID=###; />
</connectionStrings>
更多信息: http : //www.nikhilk.net/Entry.aspx?id=158
如果使用此方法,则可以照常引用配置,并且仍然可以将配置拆分为单独的文件。
我们用:
<configuration>
<appSettings>
<add key="connection.string" value="Initial Catalog=XXX;server=localhost;User=YYY;Password=ZZZ;" />
</appSettings>
</configuration>
然后:
ConfigurationManager.AppSettings["connection.string"];
将以下内容添加到您的web.config文件中,位于关闭config标记上方的底部。
<connectionStrings>
<add connectionString="Data Source=Servernamegoeshere;Initial Catalog=databasenamehere;Persist Security Info=True;User ID=***;Password=***" name="nameyouwanttogivethisconnection" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
要在主窗体的页面加载中引用连接,请使用以下命令:
public void Page_Load(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["nameyouwanttogivethisconnection"].ConnectionString;
SqlConnection SqlConnection = new SqlConnection(connectionString);
SqlCommand SqlCommand = new SqlCommand("update table etc etc....",SqlConnection);
SqlConnection.Open();
SqlCommand.ExecuteNonQuery(); //This line is for updates and inserts, use SqlCommand.ExecuteReader(CommandBehavior.CloseConnection); for select statments
SqlConnection.Close();
}
确保将这些引用添加到在以下位置使用此代码的页面顶部:
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
然后,您可以使用该连接来创建对数据库运行的Sqlcommand。
您也可以使用ApplicationSettings,而不必手动在配置文件中写入信息(这将自动完成)
当您要使用它时,只需键入
Application.Settings.Default.ConnectionString
即
SqlConnection connection = new SqlConnection(Application.Settings.Default.ConnectionString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.