c# - App.Config 连接字符串

标签 c# winforms database-connection connection-string

在我的 Windows 窗体中,我在 app.config 中有连接字符串

<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="Database"
            connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database.accdb"
            providerName="System.Data.OleDb" />
    </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

在所有类(class)中,我都使用以下代码连接到数据库。

string connString = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;

但是没有连接到数据库。

谁能指出错误。

但是当我在不使用 app.config 的情况下使用这段代码时,它工作正常。

   string connString  = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source = C:\\Users\\Amrit\\Desktop\\Database.accdb; Persist Security Info = False;";

如何使 app.config 连接字符串工作..

最佳答案

你可以这样做

<configuration>
 <appSettings>
   <add key="ApplicationTitle" value="Sample Console Application" />
   <add key="ConnectionString"
       value="Server=localhost;Database=Northwind;Integrated
              Security=false;User Id=sa;Password=;" />
</appSettings>

然后使用 ConfigurationSettings.AppSettings["ConnectionString"];

关于c# - App.Config 连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14918912/

相关文章:

c# - 如何更改 DataSet.xsd 中的连接字符串?

php - 无法连接到数据库

c# - 使用 bool(返回类型)处理异常或将异常传递给客户端?

c# - 如果不显式调用 Dispose,.NET 对象 Pen 对象将如何处理?

c# - 如何在 Windows 窗体应用程序中保存应用程序设置?

C# 缩短重复代码的更好方法

java - 如何使用java检查sqlite中是否存在与数据库的连接?

c# - .NET 4.5 Quartz 作业未触发 Global.asax.cs Application_Start

c# - 如何做有条件检查日期在C#中不能为空?

C# - 帮助自定义 DatagridView 单元格选项