vb.net - 使用 ADODB 从查询中检索值
问题描述
我正在学习调整我在 VBA 中使用的代码以在 VB.Net 中工作,而且我很难弄清楚如何从查询中获取值并将其存储在字符串中。
我知道查询有效,但是当我尝试将其存储在字符串“Valor”中时,它与 VBA 不同,会发生错误,如错误图像中所示。
Sub Main()
Dim VD As New ADODB.Connection
Dim RS As New ADODB.Recordset
Dim Valor As String
VD.ConnectionString = "DSN=XXX;UID=XXX;PWD=XXX;"
VD.Open()
RS = VD.Execute("SELECT Cod_PA FROM Tab_SERVICO WHERE Cod_PA='VIADELMAR'")
If Not (RS.BOF And RS.EOF) Then
Valor = RS.Fields("Cod_PA").Value
Else
Valor = "Não existe!"
End If
RS.Close()
VD.Close()
MsgBox(Valor)
End Sub
解决方案
Private Sub Example()
Dim VD As New System.Data.OleDb.OleDbConnection ' ADODB.Connection
Dim CMD As New System.Data.OleDb.OleDbCommand ' ADODB.Recordset
Dim Valor As String
VD.ConnectionString = "DSN=XXX;UID=XXX;PWD=XXX;"
VD.Open()
CMD.Connection = VD
CMD.CommandText = "SELECT Cod_PA FROM Tab_SERVICO WHERE Cod_PA='VIADELMAR'"
''Two (or more) possible choices for getting data:
''Option 1
''If you Then just want 1 col / 1 row, you can simply .ExecuteScalar()
Valor = CMD.ExecuteScalar 'Simple. Sometimes too simple.
''Option 2 - If your query will return multiple columns and rows then
'' you need to get data with a DataAdapter and store it
'' in a DataSet or DataTable. Example: (uncomment below)
'Dim DT As New DataTable
'Dim DA As New System.Data.OleDb.OleDbDataAdapter(CMD)
'DA.Fill(DT)
'If (DT.Rows.Count > 0) Then
' Valor = DT.Rows(0)("Cod_PA")
'Else
' Valor = "Não existe!"
'End If
''clean up. Just like: Set VD = Nothing
'DA.Dispose()
CMD.Dispose()
VD.Close()
VD.Dispose()
MsgBox(Valor)
End Sub
推荐阅读
- scala - 从 Seq[JsValue] 中过滤掉空值
- sql - 如何将数据转置到 hive
- javascript - 如何启动 1 by 1 ajax 请求
- python - 使用 python 打开 MDF4 (.mf4) 文件
- rpc - How to pass a dict parameter from Python to Frida RPC JavaScript function?
- java - 403 Forbidden 当使用@Secured Spring Security
- python - 如何在 Python 的同一张图中绘制两个或多个重叠的 3-D 高斯曲面?
- sas - compute variable after datalines
- javascript - 如何调用另一个组件中的函数(方法)?
- ios - 我可以在自定义框架中添加 Pod 吗?