C# 如何使用检索和使用设置值连接到adatabase

C# 如何使用检索和使用设置值连接到adatabase,c#,C#,我正在开发窗口应用程序,我希望应用程序的用户可以更改连接字符串,因此我创建了一个表单,以将连接字符串保存到设置并能够检索它,但问题是如何使用此设置 private void button1_Click(object sender, EventArgs e) { var serv = Properties.Settings.Default.server; var db = Properties.Settings.Default.database; var useri

我正在开发窗口应用程序,我希望应用程序的用户可以更改连接字符串,因此我创建了一个表单,以将连接字符串保存到设置并能够检索它,但问题是如何使用此设置

private void button1_Click(object sender, EventArgs e) 
{ 
    var serv = Properties.Settings.Default.server; 
    var db = Properties.Settings.Default.database; 
    var userid = Properties.Settings.Default.userid; 
    var pass = Properties.Settings.Default.password; 

    SqlConnection conn = new SqlConnection("Data Source=serv;Initial Catalog=db;User ID=userid password=pass"); 
    SqlDataAdapter sda = new SqlDataAdapter("SELECT count(*) FROM users WHERE username='" + txtUsername.Text + "' and password='" + txtPassword.Text + "'", conn); 
}
试一试


从代码片段中可以看到,连接字符串值只是传递给
SqlConnection
构造函数的
string
,因此对于您的情况,您可以在运行时提取该值并动态加载该值

虽然可以操作包含连接字符串值的
app.config
文件,但我通常更喜欢操作辅助文件。例如,更好的选择是在
XML
中使用辅助文件,并在用户更改连接字符串时对其执行类似CRUD的操作。在运行时,您可以提取它们的特定连接字符串值,并像上面所做的那样将其加载到构造函数中。示例XML结构可以如下所示:

<connections>
  <connection userID="12345">Data Source=servA;Initial Catalog=db123;User ID=jSmith password=pass1</connection>
  <connection userID="43532">Data Source=servB;Initial Catalog=db456;User ID=rJSmith password=abc321</connection>
</connections>

数据源=servA;初始目录=db123;用户ID=jSmith password=pass1
数据源=servB;初始目录=db456;用户ID=rJSmith密码=abc321
如果更改的只是用户、过程、目录和数据源值,而连接字符串的其余部分是静态的,则可以只存储这些单独的值,而不是整个连接字符串,然后在运行时动态注入这些值以构建连接字符串


当使用LINQ to XML之类的工具时,读取XML并不困难,这将允许您查询XML文件并通过
userID
字段获取特定的连接字符串。LINQ to XML的一个很好的参考是以下内容:

将连接字符串放入
App.config/Web.config
,这将使以后在需要时更容易修改

另外,请记住,通常在使用
SqlConnection
时,始终使用
using
语句

例如:

App.config/Web.config
中添加以下内容:

<appSettings>
   <add key="myConnectionString" value="Data Source=serv;Initial Catalog=db;User ID=userid password=pass" />
</appSettings>
注意

如果您愿意,也可以通过代码更改这些设置:

   private void UpdateConfig(string key, string value)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configFile.AppSettings.Settings[key].Value = value;

        configFile.Save();
    }
using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["myConnectionString"]))
{
  using(SqlCommand sqlCommandConn = new SqlCommand(InsertStatement))
  {
    sqlCommandConn.Connection = conn;
    //TODO: Open connection, Execute queries...
  }
}
   private void UpdateConfig(string key, string value)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configFile.AppSettings.Settings[key].Value = value;

        configFile.Save();
    }