首页 > 解决方案 > 使用 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

错误

标签: vb.netadodb

解决方案


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

推荐阅读