Получить счетчик из SQL - PullRequest
0 голосов
/ 05 ноября 2019

Я пытаюсь получить количество в выбранном предложении SQL, но безуспешно, как я могу получить значение?

Вот где я вызываю функцию:

Dim sql3 As String = "select COUNT(*) as countvalue from fat_prods where id_fat=" + valor.ToString + ""
Dim dadosretornados3 As System.Data.DataTableReader = buscadadosacess(sql3)
oConn.Close()

вот функция:

Function buscadadosacess(sql As String)
  oConn.ConnectionString = strConn
  oConn.Open()
  If oConn.State = ConnectionState.Open Then
    ACommand = New OleDbCommand(sql, oConn)
    'define um dataAdapter
    AAdapter = New OleDbDataAdapter()
    AAdapter.SelectCommand = ACommand
    'define e preenche um DataTable com os dados
    ATabela = New DataTable()
    AAdapter.Fill(ATabela)
    ' associar campos a base de dados
    xy = ATabela.CreateDataReader
    ' Ler da tabela
    'linha = ACommand.ExecuteReader
  End If

  'Tipo de dados incorrecto na expressão de critérios.'
  Return xy
End Function

мой вопрос, как мне получить значение счетчика? если бы это был некоторый столбец в базе данных, я бы походил на msgbox(dadosretornados("id_fat"))

, поэтому мой реальный вопрос - что мне нужно поместить внутрь dadosretornados ( HERE ), чтобы получить значение счетчика

Ответы [ 2 ]

0 голосов
/ 06 ноября 2019

Попробуйте выполнить следующее:

Private Function RowCount() As Integer
    ' Declare the object to return
    Dim count As Integer = -1

    ' Declare the connection object
    Dim con As OleDbConnection

    ' Wrap code in Try/Catch
    Try
        ' Set the connection object to a new instance
        ' TODO: Change "My Connection String Here" with a valid connection string
        con = New OleDbConnection("My Connection String Here")

        ' Create a new instance of the command object
        Using cmd As OleDbCommand = New OleDbCommand("SELECT Count([id_fat]) FROM [fat_prods] WHERE [id_fat]=@id_fat", con)
            ' Paramterize the query
            cmd.Parameters.AddWithValue("@id_fat", valor)

            ' Open the connection
            con.Open()

            ' Use ExecuteScalar to return a single value
            count = Convert.ToInt32(cmd.ExecuteScalar())

            ' Close the connection
            con.Close()
        End Using
    Catch ex As Exception
        ' Display the error
        Console.WriteLine(ex.Message)
    Finally
        ' Check if the connection object was initialized
        If con IsNot Nothing Then
            If con.State = ConnectionState.Open Then
                ' Close the connection if it was left open(exception thrown)
                con.Close()
            End If

            ' Dispose of the connection object
            con.Dispose()
        End If
    End Try

    ' Return the row count
    Return count
End Function

Эта функция либо возвращает счетчик строк, либо -1, если она не удалась. Это делается путем вызова ExecuteScalar для команды, которая возвращает единственное значение (число).

Он также очищает любые устаревшие объекты, используя оператор Using или явно вызывая метод Dispose.

0 голосов
/ 05 ноября 2019

dadosretornados ("countvalue")

ИЛИ

dadosretornados (0)

...