如何设置表适配器的连接字符串(动态设置的连接字符串)

发布于 2024-11-07 21:33:54 字数 480 浏览 0 评论 0原文

我刚刚从另一位不再在公司工作的开发人员那里继承了“数据库专家”的角色,所以如果我听起来特别菜鸟,请原谅我。

该应用程序是一个 VB.NET 4 应用程序。

我们的表适配器的数据库连接字符串是 my.settings (My.Settings.DBConnectionString) 中的一个字符串,该字符串是在运行时设置的。当我必须修改表适配器时,它们在 My.Settings.DBConnectionString 中看不到任何数据,因此不允许我编辑它们,直到我设置“真实”(或硬编码)连接字符串。现在我想将其改回动态设置的,但 Visual Studio 似乎不想让我这样做。我相信我已经在 .xsd 文件后面的自动生成代码中找到了能够更改特定表适配器的连接字符串的位置,但如果我这样做会发生不好的事情吗?或者除了我不知道的 Visual Studio 一侧的属性窗格之外,是否还有其他一些机制可以更改表适配器的连接字符串?

作为次要问题,这里是否存在不良/非最佳实践?

谢谢!

I just inherited the role of "Database Guy" from another developer who is no longer with the company, so please forgive me if I sound particularly noobish.

The application is a VB.NET 4 application.

The DB connection string for our table adapters was a string in my.settings (My.Settings.DBConnectionString) that is being set at runtime. When I had to modify the table adapters they couldn't see any data in My.Settings.DBConnectionString and thus did not allow me to edit them until I set a "real" (or hard-coded) connection string. Now I want to change it back to the dynamically set one, but Visual Studio doesn't seem to want to let me do that. I believe I've found the spot in the auto-generated code behind the .xsd file to be able to change the connection string for a particular table adapter, but if I do that will bad things happen? Or is there some other mechanism for changing a table adapter's connection string other than the properties pane on the side of Visual Studio that I am not aware of?

Just as a secondary question, are there bad / not-best practices going on here?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

故事与诗 2024-11-14 21:33:56

这听起来像是您的表适配器的连接字符串是由

我不太清楚你动态设置它们的意思,但听起来你可能遇到过经常有争议的(我知道,需要引用......)功能,这意味着你无法设置应用程序运行时的范围设置。这是因为自动生成的类为您的应用程序设置提供只读属性。可以更改用户范围设置(有关详细信息,请参阅前面的链接)。

有一个帖子讨论更改可能有用的应用程序设置。

如果您确实需要在运行时更改应用程序设置,那么可能值得实现您自己的设置机制,该机制使用 XML、注册表或其他内容来存储、检索和更改设置。

希望有帮助

编辑:

我突然想到我没有正确阅读你的问题。不仅您的连接字符串可能源自应用程序设置,而且您的表适配器也可能绑定到该连接字符串?如果是这样,请参阅这篇文章,其中解释了如何您可以注入/更改表适配器的连接字符串。对我来说似乎有点黑客,但它应该有效。

This sounds like your table adapter's connection string is being set by an application setting?

I'm not sure quite what you mean by setting them dynamically, but it sounds like you may have come across the often disputed (I know, citation needed...) feature that means you cannot set application scope settings at runtime. This is because the auto-generated classes provide readonly properties for your app settings. User scope settings can be changed (see previous link for details).

There is a post here discussing changing application settings which may be of use.

If you do need to change application settings at runtime, it may be worth implementing your own settings mechanism which uses XML, the Registry, or something else to store, retrieve, and change settings.

Hope that helps

EDIT:

Suddenly occurred to me that I hadn't read your question properly. Not only is your connection string probably derived from an application setting, but perhaps your table adapter is bound to that connection string? If so, see this post which explains how you can inject/change the connection string for table adapters. Seems like a bit of a hack to me, but it should work.

谷夏 2024-11-14 21:33:56

以下是我如何使用 VB 中的模块从 INI 文件更新连接字符串,该模块显示了更新连接字符串的稍微不同的方法。

它允许客户端从应用程序中的表单更新连接。表单上的文本框与模块中的公共字符串相关联。按表单上的“保存”按钮会调用模块中的savedbsetup 方法。然后,应用程序启动时,它会从创建的 INI 文件加载新设置

Imports System.Configuration
Imports System.Environment
Imports System.IO
Module SetupOptions
    Public DBJacksServer As String = "CSTDesktop1\SQLExpress"
    Public DBJacksCatalog As String = "PreJacks"
    Public DBJacksUserName As String = "sa"
    Public DBJacksPassword As String = "dba"
    Public appData As String = $"{GetFolderPath(SpecialFolder.ApplicationData)}/CSTSoftware/Jacks"
    Public DBJacksSetUpFile As String = $"{appData}/DBJackssetup.ini"
    Public DBConnectionStringSettingsName As String = "Jacks.My.MySettings.PreJacksConnectionString"
    Public Sub SaveDBSetup()
        Try
            If Not Directory.Exists(appData) Then
                Directory.CreateDirectory(appData)
            End If
            If File.Exists(DBJacksSetUpFile) Then
                File.Delete(DBJacksSetUpFile)
            End If
            Using sw As StreamWriter = New StreamWriter(DBJacksSetUpFile)
                sw.WriteLine(DBJacksServer)
                sw.WriteLine(DBJacksCatalog)
                sw.WriteLine(DBJacksUserName)
                sw.WriteLine(DBJacksPassword)
            End Using
        Catch ex As Exception
            MessageBox.Show($"Failed to Save DB Settings With this Error: {ex.Message}")
        End Try

    End Sub
Public Sub LoadDBSetup()
    Try
        If File.Exists(DBJacksSetUpFile) Then
            Using sr As StreamReader = New StreamReader(DBJacksSetUpFile)
                DBJacksServer = sr.ReadLine()
                DBJacksCatalog = sr.ReadLine()
                DBJacksUserName = sr.ReadLine()
                DBJacksPassword = sr.ReadLine()
            End Using
            SetDBJacksConnection()
        End If
    Catch ex As Exception
        MessageBox.Show($"Failed to Load DB Settings With this Error: {ex.Message}")
    End Try

End Sub
Public Function GetDBJacksConnection() As String
    'If File.Exists(DBJacksSetUpFile) Then
    '    Return $"Data Source={DBJacksServer};Initial Catalog={DBJacksCatalog};Persist Security Info=True;User ID={DBJacksUserName};Password={DBJacksPassword}"
    'Else
    Return ConfigurationManager.ConnectionStrings(DBConnectionStringSettingsName).ConnectionString
    'End If
End Function
Public Sub SetDBJacksConnection()
    Dim config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
    Dim csSection = config.ConnectionStrings
    csSection.ConnectionStrings(DBConnectionStringSettingsName).ConnectionString = $"Data Source={DBJacksServer};Initial Catalog={DBJacksCatalog};Persist Security Info=True;User ID={DBJacksUserName};Password={DBJacksPassword}"
    config.Save(ConfigurationSaveMode.Modified)
    ConfigurationManager.RefreshSection("connectionStrings")
End Sub
End Module

Here is how I updated a Connectionstring from a INI file with a Module in VB that shows a slightly different way to update the connectionstring.

It allows the client to update the connection from a form in the application. The textboxes on the form are tied to the Public strings in the module. Pressing the save button on the form calls the savedbsetup method in the module. Then the time the app is launched, it loads the new settings from the created INI file

Imports System.Configuration
Imports System.Environment
Imports System.IO
Module SetupOptions
    Public DBJacksServer As String = "CSTDesktop1\SQLExpress"
    Public DBJacksCatalog As String = "PreJacks"
    Public DBJacksUserName As String = "sa"
    Public DBJacksPassword As String = "dba"
    Public appData As String = $"{GetFolderPath(SpecialFolder.ApplicationData)}/CSTSoftware/Jacks"
    Public DBJacksSetUpFile As String = $"{appData}/DBJackssetup.ini"
    Public DBConnectionStringSettingsName As String = "Jacks.My.MySettings.PreJacksConnectionString"
    Public Sub SaveDBSetup()
        Try
            If Not Directory.Exists(appData) Then
                Directory.CreateDirectory(appData)
            End If
            If File.Exists(DBJacksSetUpFile) Then
                File.Delete(DBJacksSetUpFile)
            End If
            Using sw As StreamWriter = New StreamWriter(DBJacksSetUpFile)
                sw.WriteLine(DBJacksServer)
                sw.WriteLine(DBJacksCatalog)
                sw.WriteLine(DBJacksUserName)
                sw.WriteLine(DBJacksPassword)
            End Using
        Catch ex As Exception
            MessageBox.Show($"Failed to Save DB Settings With this Error: {ex.Message}")
        End Try

    End Sub
Public Sub LoadDBSetup()
    Try
        If File.Exists(DBJacksSetUpFile) Then
            Using sr As StreamReader = New StreamReader(DBJacksSetUpFile)
                DBJacksServer = sr.ReadLine()
                DBJacksCatalog = sr.ReadLine()
                DBJacksUserName = sr.ReadLine()
                DBJacksPassword = sr.ReadLine()
            End Using
            SetDBJacksConnection()
        End If
    Catch ex As Exception
        MessageBox.Show($"Failed to Load DB Settings With this Error: {ex.Message}")
    End Try

End Sub
Public Function GetDBJacksConnection() As String
    'If File.Exists(DBJacksSetUpFile) Then
    '    Return $"Data Source={DBJacksServer};Initial Catalog={DBJacksCatalog};Persist Security Info=True;User ID={DBJacksUserName};Password={DBJacksPassword}"
    'Else
    Return ConfigurationManager.ConnectionStrings(DBConnectionStringSettingsName).ConnectionString
    'End If
End Function
Public Sub SetDBJacksConnection()
    Dim config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
    Dim csSection = config.ConnectionStrings
    csSection.ConnectionStrings(DBConnectionStringSettingsName).ConnectionString = $"Data Source={DBJacksServer};Initial Catalog={DBJacksCatalog};Persist Security Info=True;User ID={DBJacksUserName};Password={DBJacksPassword}"
    config.Save(ConfigurationSaveMode.Modified)
    ConfigurationManager.RefreshSection("connectionStrings")
End Sub
End Module
孤独患者 2024-11-14 21:33:55

这是我解决运行时更改连接字符串问题的方法。希望这有帮助。

在我的设置中,我有 2 个条目
在此处输入图像描述

我有一个名为 DataSet1 的数据集

在此处输入图像描述

我有 3 个表单,分别称为 Form1、Form2 和 Form3

Form1 具有以下控件

在此处输入图像描述

以及以下代码

Public Class Form1

    Private Sub GenericoBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles GenericoBindingNavigatorSaveItem.Click
        Me.Validate()
        Me.GenericoBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DataSet1)

    End Sub



    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Me.TableAdapterManager.Connection.ConnectionString = My.MySettings.Default._001NewConnectionString

        Me.TableAdapterManager.UpdateAll(Me.DataSet1)

        Label5.Text = My.MySettings.Default._001NewConnectionString

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        My.MySettings.Default("_001NewConnectionString") = "Data Source=" & TextBox1.Text & "\" &
            TextBox2.Text & ";Initial Catalog=001;Persist Security Info=True;User ID=" &
            TextBox3.Text & ";Password=" & TextBox4.Text
        My.MySettings.Default.Save()

        Me.TableAdapterManager.Connection.ConnectionString = My.MySettings.Default._001NewConnectionString
        Me.TableAdapterManager.UpdateAll(Me.DataSet1)

        Try
            Me.GenericoTableAdapter.Fill(Me.DataSet1.generico)
        Catch ex As Exception
            MessageBox.Show("error Form1")
        End Try
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim f As New Form2(TableAdapterManager.Connection.ConnectionString)
        f.ShowDialog()

    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim f As New Form3(TableAdapterManager.Connection.ConnectionString)
        f.ShowDialog()
    End Sub
End Class

Form2 具有以下控件

在此处输入图像描述

具有以下代码

Public Class Form2

    Private Sub UtentesBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles UtentesBindingNavigatorSaveItem.Click
        Me.Validate()
        Me.UtentesBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DataSet1)

    End Sub
    Public Sub New(ConnectionString As String)
        InitializeComponent()
        Me.TableAdapterManager.Connection.ConnectionString = ConnectionString
        Me.TableAdapterManager.UpdateAll(Me.DataSet1)
    End Sub




    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Try
            Me.UtentesTableAdapter.Fill(Me.DataSet1.utentes)
        Catch ex As Exception
            MessageBox.Show("Form2")
        End Try



    End Sub
End Class

Form3 有以下控件

在此处输入图像描述

具有以下代码

Public Class Form3
    Public Sub New(ConnectionString As String)
        InitializeComponent()
        Me.TableAdapterManager.Connection.ConnectionString = ConnectionString
        Me.TableAdapterManager.UpdateAll(Me.DataSet1)
    End Sub
    Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Me.UtentesTableAdapter.Fill(Me.DataSet1.utentes)
        Catch ex As Exception
            MessageBox.Show("Form3")
        End Try


    End Sub

    Private Sub UtentesBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles UtentesBindingNavigatorSaveItem.Click
        Me.Validate()
        Me.UtentesBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DataSet1)

    End Sub
End Class

Here is how I solved the problem of changing the connection string at runtime. Hope this helps.

In my settings, I have 2 entries
enter image description here

I have a Dataset called DataSet1

enter image description here

I have 3 forms called Form1, Form2 and Form3

Form1 has the following controls

enter image description here

And the following code

Public Class Form1

    Private Sub GenericoBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles GenericoBindingNavigatorSaveItem.Click
        Me.Validate()
        Me.GenericoBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DataSet1)

    End Sub



    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Me.TableAdapterManager.Connection.ConnectionString = My.MySettings.Default._001NewConnectionString

        Me.TableAdapterManager.UpdateAll(Me.DataSet1)

        Label5.Text = My.MySettings.Default._001NewConnectionString

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        My.MySettings.Default("_001NewConnectionString") = "Data Source=" & TextBox1.Text & "\" &
            TextBox2.Text & ";Initial Catalog=001;Persist Security Info=True;User ID=" &
            TextBox3.Text & ";Password=" & TextBox4.Text
        My.MySettings.Default.Save()

        Me.TableAdapterManager.Connection.ConnectionString = My.MySettings.Default._001NewConnectionString
        Me.TableAdapterManager.UpdateAll(Me.DataSet1)

        Try
            Me.GenericoTableAdapter.Fill(Me.DataSet1.generico)
        Catch ex As Exception
            MessageBox.Show("error Form1")
        End Try
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim f As New Form2(TableAdapterManager.Connection.ConnectionString)
        f.ShowDialog()

    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim f As New Form3(TableAdapterManager.Connection.ConnectionString)
        f.ShowDialog()
    End Sub
End Class

Form2 has the following controls

enter image description here

with the following code

Public Class Form2

    Private Sub UtentesBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles UtentesBindingNavigatorSaveItem.Click
        Me.Validate()
        Me.UtentesBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DataSet1)

    End Sub
    Public Sub New(ConnectionString As String)
        InitializeComponent()
        Me.TableAdapterManager.Connection.ConnectionString = ConnectionString
        Me.TableAdapterManager.UpdateAll(Me.DataSet1)
    End Sub




    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Try
            Me.UtentesTableAdapter.Fill(Me.DataSet1.utentes)
        Catch ex As Exception
            MessageBox.Show("Form2")
        End Try



    End Sub
End Class

and Form3 has the following controls

enter image description here

with the following code

Public Class Form3
    Public Sub New(ConnectionString As String)
        InitializeComponent()
        Me.TableAdapterManager.Connection.ConnectionString = ConnectionString
        Me.TableAdapterManager.UpdateAll(Me.DataSet1)
    End Sub
    Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Me.UtentesTableAdapter.Fill(Me.DataSet1.utentes)
        Catch ex As Exception
            MessageBox.Show("Form3")
        End Try


    End Sub

    Private Sub UtentesBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles UtentesBindingNavigatorSaveItem.Click
        Me.Validate()
        Me.UtentesBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DataSet1)

    End Sub
End Class
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文