连接字符串真的很烦人。
我在一个解决方案中共同拥有两个项目。 Web表单应用程序充当表示层,以及支持它的类库,它将从数据库发送和接收数据。
- 类库项目中的员工类 -
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 / app配置文件添加到类库中以在该项目中存储连接字符串?
答案 0 :(得分:16)
不清楚示例中My_ConnectionString
的来源,但请尝试此
System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString
Dim DBConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString)
答案 1 :(得分:5)
如果它是.mdf数据库并且连接字符串在创建时已保存,您应该可以通过以下方式访问它:
Dim cn As SqlConnection = New SqlConnection(My.Settings.DatabaseNameConnectionString)
希望能有所帮助。
答案 2 :(得分:0)
Public Function connectDB() As OleDbConnection
Dim Con As New OleDbConnection
'Con.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=" & DBNAME & ";Data Source=" & DBSERVER & ";Pwd=" & DBPWD & ""
Con.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBNAME;Data Source=DBSERVER-TOSH;User ID=Sa;Pwd= & DBPWD"
Try
Con.Open()
Catch ex As Exception
showMessage(ex)
End Try
Return Con
End Function
答案 3 :(得分:0)
APPConfig中的连接
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com" providerName="System.Data.SqlClient" />
</connectionStrings>
在Class.Cs
public string ConnectionString
{
get
{
return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
}
答案 4 :(得分:0)
我不知道这是否仍然是一个问题,但是我更喜欢仅在代码中使用My.Settings。
Visual Studio生成一个具有用于从app.config文件读取设置的函数的简单类。
您只需使用My.Settings.ConnectionString即可访问它。
Using Context As New Data.Context.DataClasses()
Context.Connection.ConnectionString = My.Settings.ConnectionString
End Using