0

我正在使用 c# 构建桌面应用程序,我将连接字符串放在 app.config 文件中,如下所示

 <connectionStrings>
        <add name="ComputerManagement" 
        connectionString="Provider=Microsoft.ACE.OLEDB.12.0; Data Source=...;Initial Catalog=Computersh;Integrated Security=True"/>
      </connectionStrings>

如何在表单中调用连接字符串?

4

4 回答 4

1

您可以通过以下方式获取连接字符串ConfigurationManager

using System.Configuration;
var connection = ConfigurationManager.ConnectionStrings["ComputerManagement"];

但是您仍然需要使用一些东西来连接到数据库,例如:http SqlConnection: //msdn.microsoft.com/en-gb/library/system.data.sqlclient.sqlconnection.aspx

using System.Configuration;
using System.Data.SqlClient;

var connection = ConfigurationManager.ConnectionStrings["ComputerManagement"];

if (connection != null) 
{
    using (var sqlcon = new SqlConnection(connection.ConnectionString))
    {
        ...
    }
}
于 2013-02-19T11:13:55.757 回答
0

参考System.Configuration和使用

System.Configuration.ConfigurationManager
      .ConnectionStrings["ComputerManagement"].ConnectionString
于 2013-02-19T11:14:00.260 回答
0

像这样:

var constring = ConfigurationManager.ConnectionStrings["ComputerManagement"].ConnectionString;

你也必须添加这个using System.Configuration;:)

于 2013-02-19T11:14:04.370 回答
0

使用ConfigurationManager应该就足够了:

var connection = ConfigurationManager.ConnectionStrings["ComputerManagement"];

null然后,在访问实际字符串之前检查, :

if (connection != null) {
  var connectionString = connection.ConnectionString;
}
于 2013-02-19T11:14:11.740 回答