提问人:Redgren Grumbholdt 提问时间:4/12/2019 更新时间:11/17/2023 访问量:4149
如何使用命令从 SQL 查询中获取单行/记录。VB.NET 中的 ExecuteScalar
How to get single row/record from a SQL query using command.ExecuteScalar in VB.NET
问:
我试图通过执行带有主键的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
答:
2赞
Steve
4/12/2019
#1
ExecuteScalar 返回具有单个列的单行,但不返回从中获取数据的 DataReader。相反,它直接将该单个值作为 Object 返回。如果查询未找到与 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 aren'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
评论
0赞
Redgren Grumbholdt
4/12/2019
我可以同时从多个列中获取值吗?
0赞
Steve
4/12/2019
是的,但随后使用 ExecuteReader 而不是 ExecuteScalar
0赞
Redgren Grumbholdt
4/12/2019
我得到了Object reference not set to an instance of an object.
0赞
Steve
4/12/2019
这句话只是一个例子。但是,如果确实有一个last_name字段,并且该字段可能为 null,则应检查它是否包含值(在调用 ToString 之前使用 IsDBNull)
0赞
Redgren Grumbholdt
4/12/2019
让我们在聊天中继续讨论。
评论