使用并调用/c#形式的连接字符串
本文关键字:连接 字符串 调用 | 更新日期: 2023-09-27 18:00:00
我正在使用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"];
但是您仍然需要使用一些东西来连接到数据库,例如SqlConnection
:http://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;
:)
使用ConfigurationManager
就足够了:
var connection = ConfigurationManager.ConnectionStrings["ComputerManagement"];
然后,在访问实际字符串之前,检查null
if (connection != null) {
var connectionString = connection.ConnectionString;
}