从VB.net中的数据表中选择条件

时间:2013-09-23 14:17:42

标签: sql vb.net datatable

我想根据同一行中另一个字段的值从VB中的数据表中选择某个字段。

在SQL中,可以通过编写此查询轻松完成:

select error_message from table_errors where error_case="condition"

如果我在VB中填充数据表中的SQL表,我该怎么做? 如何在数据表中基于项目(“error_Case”)字段选择项目(“error_message”)?

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:3)

您可以使用Linq-To-DataSet

Dim matchingRows As IEnumerable(Of DataRow) = 
    From row In table
    Where row.Field(Of String)("error_case") = "condition"

如果你只想要一个专栏(当然也可以一步完成):

Dim errorMessages As IEnumerable(Of String) = 
    From row In matchingRows 
    Select row.Field(Of String)("error_message")

For Each error In errorMessages 
    Console.WriteLine(error)
Next 

如果您希望它只是一行,请使用FirstSingle(如果有多行,则抛出异常):

Dim error As String = errorMessages.First()

如果序列为空,First会抛出异常,您可以使用FirstOrDefault

Dim error As String = errorMessages.FirstOrDefault() ' is null/Nothing in case of an empty sequence 

全部在一行中(注意Linq和DataTable.Select都需要使用循环):

Dim ErrMessage As String = errorTable.AsEnumerable().
    Where(Function(r) r.Field(Of String)("Error_Case") = TextCase.Text).
    Select(Function(r) r.Field(Of String)("Error_Message")).
    FirstOrDefault()

答案 1 :(得分:0)

这是粗略代码的工人版本

    Dim connString As String = "select error_message from table_errors where error_case='condition'"
    Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(connString)
    conn.Open()
    Dim cmd As SqlClient.SqlCommand = New SqlClient.SqlCommand(connString, conn)
    Dim dTable As DataTable = New DataTable()
    Dim dAdapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(cmd)
    dAdapter.Fill(dTable)
    conn.Close()
    Dim text As String
    Dim dReader As DataTableReader = dTable.CreateDataReader()
    While dReader.Read()
        text = dReader.GetValue(0)
    End While
    dReader.Close()