如何在VB.NET中使用command.ExecuteScalar从SQL查询中获取单行/记录

时间:2019-04-12 09:55:53

标签: vb.net sqlite ado.net executescalar

我试图通过执行带有主键的SELECT语句来获得单行

我尝试将command.ExecuteScalar()的输出分配给Object变量,然后尝试通过像obj('column_name')这样的键访问值。

Using conn As New SQLiteConnection(connectionString:=connection.get_connection_string())
                    conn.Open()
    Dim sql_string As String = "SELECT * FROM employees WHERE id = @id"
    Using cmd As New SQLiteCommand(connection:=conn, commandText:=sql_string)
        cmd.Parameters.AddWithValue("@id", employee_id)
        Dim reader As Object = cmd.ExecuteScalar()
        If reader <> Nothing Then
            Me.user_details(2) = reader("first_name")
        End If
    End Using
End Using

我原本希望从first_name获得reader('first_name')列中的值,但是却遇到了NullReferenceException异常

1 个答案:

答案 0 :(得分:1)

ExecuteScalar返回具有单列的单行,但不返回用于获取数据的DataReader。而是直接将单个值作为对象返回。如果查询找不到与Where语句匹配的行,则此对象为Nothing

如果只想获取名字,则应将查询文本更改为

Dim sql_string As String = "SELECT first_name FROM employees WHERE id = @id"
Using cmd As New SQLiteCommand(connection:=conn, commandText:=sql_string)
    cmd.Parameters.AddWithValue("@id", employee_id)
    Dim result As Object = cmd.ExecuteScalar()
    If result <> Nothing Then
        Me.user_details(2) = result.ToString()
    End If
End Using

相反,如果要从该记录中检索所有字段(或多个字段),请使用ExecuteReader,然后开始使用

读取结果。
Dim sql_string As String = "SELECT first_name, last_name, city FROM employees WHERE id = @id"
Using cmd As New SQLiteCommand(connection:=conn, commandText:=sql_string)
    cmd.Parameters.AddWithValue("@id", employee_id)
    Dim reader = cmd.ExecuteReader()
    ' Try to position the reader on the first record returned by the query
    ' if there isn't records the Read returns false. 
    ' You can also test this with reader.HasRows
    While reader.Read()
        Me.user_details(1) = reader("last_name").ToString()
        Me.user_details(2) = reader("first_name").ToString()
        Me.user_details(3) = reader("city").ToString()
    End While
End Using