将 VBA 函数转换为 VB.net 以获得 sql 数据

Converting VBA function to VB.net to get sql data

我正在尝试将 VBA 代码转换为 VB.net,我已经做到了,但我无法将结果集转换为 vb.net。 RS 在 VBA 中是 'dim as resultset',以为我可以将它更改为数据集,但我在使用“.fields”和其他选项时遇到错误?

 Function GetG(sDB As String, sServ As String, sJob As String) As String

        'sDB = Database name, sServ = Server\Instance, path = job.path
        Dim conString As String = ("driver={SQL Server};server = " & 
         TextBox1.Text & " ; uid = username;pwd=password:database = " & 
         TextBox2.Text)
        Dim RS As DataSet
        Dim conn As SqlConnection = New SqlConnection(conString)
        Dim cmd As SqlCommand


        conn.Open()

'This is where my problems are occuring

        cmd = New SqlCommand("SELECT [ID],[Name] FROM dbo.PropertyTypes")

           Do While Not RS.Tables(0).Rows.Count = 0
            If RS.Fields(1).Value = sJob Then
                GetG = RS.Fields(0).Value
                GetG = Mid(GetG, 2, 36)
                Exit Do
            End If
            DataSet.MoveNext

        Loop
        conn.Close
    End Function

您似乎没有填充数据集。因此,当您尝试遍历它时,它未初始化或为空。

查看此答案以查看示例:Get Dataset from DataBase

根据我的理解和一些猜测,这是我想出的我认为你想要的东西。

正如我在上面的评论中所述,您似乎可以只使用 WHERE 子句来获取您想要的确切记录(假设 sJob 的单个实例出现在名称列中)。

根据输入参数而不是表单上的控件构建连接字符串。这就是为什么您允许传递参数的原因。另请注意,有一个可能感兴趣的 SqlCommandBuilder 对象。但现在

Function GetG(sDB As String, sServ As String, sJob As String) As String
    'we'll pretend your connectionstring is correct based off of the sDB and sServ arguments
    Dim conStr As String = ("driver={SQL Server};server = " & sServ & " ; uid = username;pwd=password:database = " & sDB)
    'Create a connection and pass it your conStr
    Using con As New SqlConnection(conStr)
        con.Open() 'open the connection
        'create your sql statement and add the WHERE clause with a parameter for the input argument 'sJob'
        Dim sql As String = "SELECT [ID], [Name] FROM dbo.PropertyTypes WHERE [Name] = @job"
        'create the sqlCommand (cmd) and pass it your sql statement and connection
        Using cmd As New SqlCommand(sql, con)
            'add a parameter so the command knows what @job holds
            cmd.Parameters.Add(New SqlParameter("@job", SqlDbType.VarChar)).Value = sJob
            'Now that have the command built, we can pass it to a reader object 
            Using rdr As SqlDataReader = cmd.ExecuteReader
                rdr.Read()
                'i admin i'm a little confused here on what you are
                'trying to achieve so ID may not be what you are
                'really wanting to get a substring of.
                Return rdr("ID").ToString.Substring(2, 36)
            End Using
        End Using
    End Using
End Function

查看这是否有效的示例可以是调用消息框来显示结果。对于此示例,我将假装 TextBox3 包含您想要的 sJob。有了这些知识,你可以简单地做:

MessageBox.Show(GetG(TextBox2.Text, TextBox1.Text, TextBox3.Text))

这应该会在消息框中产生结果。