在运行时更改连接字符串

问题描述 投票:0回答:1

这是我在这里的第一篇文章,所以我很抱歉我做错了什么。 我正在开发一个由其他人启动的 Visual Basic 项目,我现在的最终任务是制作一个面板,允许用户修复 SQL 数据库的连接字符串(如果错误)。我从下面制作了面板,它将当前连接字符串分解为服务器名称、用户、密码和数据库名称。我想让保存按钮在 My.Settings 中更改此设置。如果我能完成这项任务,我将不胜感激,因此非常感谢任何帮助。另外,如果有任何其他方法可以在运行时更改连接字符串,那也很好。 预先感谢您的帮助,祝您有美好的一天! the panel I made

c# .net vb.net runtime connection-string
1个回答
0
投票

最后我找到了如何处理它,下一个代码可以工作(发布它以防有一天有人需要这个)。为了保存更改,我还必须重建项目。所以,代码是:

 Public Sub btSave_Click(sender As Object, e As EventArgs) Handles btSave.Click
    Dim connectionString As String = String.Format("Data Source = " & txtServer.Text & " ; Initial Catalog = " & txtBD.Text &
                                                   " ; Persist Security Info = True; User ID = " & txtUser.Text & " ; Password = " & txtPassword.Text & " ;")
    Dim builder As New SqlClient.SqlConnectionStringBuilder
    builder.DataSource = txtServer.Text
    builder.InitialCatalog = txtBD.Text
    builder.UserID = txtUser.Text
    builder.Password = txtPassword.Text
    Try
        Dim cnn_conn As New SqlClient.SqlConnection
        cnn_conn.ConnectionString = builder.ConnectionString
        If cnn_conn.State = ConnectionState.Closed Then
            cnn_conn.Open()
            Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
            config.ConnectionStrings.ConnectionStrings("[name of your connection string]").ConnectionString = builder.ConnectionString
            config.ConnectionStrings.ConnectionStrings("[name of your connection string]").ProviderName = "System.Data.SqlClient"
            config.Save(ConfigurationSaveMode.Modified)
            MessageBox.Show("String successfully saved", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub

Private Sub btTest_Click(sender As Object, e As EventArgs) Handles btTest.Click
    Dim connectionString As String = String.Format("Data Source = " & txtServer.Text & " ; Initial Catalog = " & txtBD.Text &
                                                  " ; Persist Security Info = True; User ID = " & txtUser.Text & " ; Password = " & txtPassword.Text & " ;")
    Dim builder As New SqlClient.SqlConnectionStringBuilder
    builder.DataSource = txtServer.Text
    builder.InitialCatalog = txtBD.Text
    builder.UserID = txtUser.Text
    builder.Password = txtPassword.Text
    Try
        Dim cnn_conn As New SqlClient.SqlConnection
        cnn_conn.ConnectionString = builder.ConnectionString
        If cnn_conn.State = ConnectionState.Closed Then
            cnn_conn.Open()
            MsgBox("Conection set", MsgBoxStyle.Information, "Message")
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.