【发布时间】:2019-08-25 05:14:33
【问题描述】:
我正在尝试将 VBA 代码转换为 VB.net,我已经做到了,但我无法将结果集转换为 vb.net。 RS 在 VBA 中是“暗淡的结果集”,我认为我可以将其更改为数据集,但在“.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
【问题讨论】:
-
SqlConnection和SqlCommand实现IDisposable并应包裹在Using块中;conn.Close不需要拼写出来,处理连接(退出Using范围)会解决这个问题。 -
您还可以在 SQL 语句中创建 WHERE 子句,以仅提取具有 sJob 值的行。这将大大减少您的代码,甚至可能不需要 do while 循环,具体取决于您的表中是否有多个具有相同 sJob 值的行。