繁体   English   中英

使用并调用表单/ c#中的连接字符串

[英]Use and call the connection string in the forms/ c#

我正在使用c#构建桌面应用程序,像这样将连接字符串放入app.config文件中

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

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

您可以使用ConfigurationManager获取连接字符串:

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

但是您仍然需要使用一些东西来与它连接到数据库,例如SqlConnectionhttp : //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))
    {
        ...
    }
}

参考System.Configuration和使用

System.Configuration.ConfigurationManager
      .ConnectionStrings["ComputerManagement"].ConnectionString

像这样:

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

另外,您还必须using System.Configuration;添加它using System.Configuration; :)

使用ConfigurationManager应该足以:

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

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

if (connection != null) {
  var connectionString = connection.ConnectionString;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM