VB.NET连接字符串(Web.Config,App.Config)

标签 vb.net connection-string

连接字符串确实很烦人。

我在一个解决方案中有两个项目。一个Web窗体应用程序充当表示层,并提供一个支持它的类库,该类库将从数据库发送和接收数据。

-类(class)图书馆项目中的员工类(class)-

Friend Class Employee

Public Function GetEmployees() As DataSet

    Dim DBConnection As New SqlConnection(My_ConnectionString)
    Dim MyAdapter As New SqlDataAdapter("exec getEmployees", DBConnection)

    Dim EmployeeInfo As DataSet
    MyAdapter.Fill(EmployeeInfo, "EmployeeInfo")

    Return EmployeeInfo

End Function

End Class

当前,应用程序告诉我它无法访问“My_ConnectionString”,我试图将其存储在配置文件中以便快速重复访问:
<configuration>

<system.web>
  <compilation debug="true" strict="false" explicit="true" targetFramework="4.5" />
  <httpRuntime targetFramework="4.5"  />
</system.web>

 <connectionStrings>
   <add name="My_ConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=My_DB;Integrated Security=True;"/>
 </connectionStrings>

</configuration>

web.config是Web表单项目的一部分,而不是类库的一部分,这些项目是否无法彼此“交谈”?我是否需要将Web/应用程序配置文件添加到类库中以在该项目中存储连接字符串?

最佳答案

不清楚您的示例中My_ConnectionString的来源,但是尝试一下
System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString
像这样

Dim DBConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString)

关于VB.NET连接字符串(Web.Config,App.Config),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15446175/

相关文章:

c# - 是否可以(以及如何)在 C# 中的运行时将 ConnectionString 添加到 app.config?

c# - 包装另一个流的 Stream 的实现

vb.net - RDLC 报告中的外部图像

azure - sitefinity azure 部署无法连接到数据库

mysql - 外部系统:配置连接以访问 MySQL 数据库

.net - 真正通用的数据链接在哪里?

c# - 在正在运行的桌面应用程序上模拟用户操作

c# - 使用 VALUE 作为单元格颜色

.net - 任何语言的所有国家/地区列表?

c# - 连接字符串抛出空引用异常?