目前,我的应用程序中的每个表单都有SQL连接字符串,如下所示:
Dim cnx As New SqlConnection("Server = SERVERNAME\SQLSERVEREXPRESS; " &
"Database = DatabaseName; " &
"Trusted_Connection = True;")
Dim cmd As SqlCommand
Dim sdr As SqlDataReader
问题是当我需要更改它时,我必须在应用程序的每个表单中执行此操作。有什么更好的方法可以做到这一点?
谢谢!
修改
我最终使用Christopherous 5000的答案翻译成VB.NET:
Public Shared Function GetConnectionString(name As String) As String
Dim connectionString = ConfigurationManager.ConnectionStrings(name)
If connectionString Is Nothing OrElse String.IsNullOrEmpty(connectionString.ConnectionString) Then
Throw New ConfigurationErrorsException(String.Format("No connection string for '{0}' found", name))
End If
Return connectionString.ConnectionString
End Function
答案 0 :(得分:1)
您应该使用web.config文件来存储连接字符串(如果需要,可以加密)
在需要连接时,我使用这个静态方法的辅助类;
public static string GetConnectionString(string name)
{
var connectionString = ConfigurationManager.ConnectionStrings[name];
if (connectionString == null || string.IsNullOrEmpty(connectionString.ConnectionString))
throw new ConfigurationErrorsException(string.Format("No connection string for '{0}' found", name));
return connectionString.ConnectionString;
}
答案 1 :(得分:0)
App.config或Web.config取决于项目是有意义的。如果您不希望将编译的代码保密,那么您想要烘焙自己的实现。 Accessing database connection string using app.config in C# winform