vb net将多个datareader结果存储到一个字符串变量中

时间:2014-01-25 06:51:40

标签: mysql vb.net executereader

我有SELECT ITEM FROM DETAIL WHERE TID="1"之类的查询。 这将返回结果,如

m4,c1,f2,d5,k2

我正在使用DATAREADER来获取多值结果

这是代码

Dim res as string = "SELECT ITEM FROM DETAIL WHERE TID='1'"
CMD = New MySqlCommand(res, con)
result = CMD.ExecuteReader()
while result.HasRows
  result.Read()
  array(indeks) = result("ITEM")
end while

现在将结果逐个存储到每个数组的索引中,

阵列(0)= M4

阵列(1)= C1 下,.....

我想将所有内容存储到单个字符串变量格式,如'm4','c1','f2','d5','k2'

格式是单引号和逗号(,)作为每个结果的分隔符,如上例所示(只有在仍有结果的情况下才显示逗号

我怎么能在vb.net中这样做?我正在使用mysql作为数据库

更新代码

    Dim cnt As String = "select count(*) from detail where kode_faktur= '" & 1 & "' "
    Dim max As Int32
    CMD_sup = New MySqlCommand(cnt, conn.konek)
    max = Convert.ToInt32(CMD_sup.ExecuteScalar())
    CMD_sup.Connection.Close()

    Dim result As MySqlDataReader

    Dim resultString As String
    Dim isFirstResult = True

    Dim arayITEM() As String
    Dim res As String = "select kode_brg from detail where kode_faktur= '" & 1 & "' "
    CMD = New MySqlCommand(res, conn.konek)
    result = CMD.ExecuteReader()


    ReDim arayITEM(max)
    If result.HasRows Then
        For i As Integer = 0 To max - 1
            result.Read()
            arayITEM(i) = result("kode_brg")
        Next
    End If

    resultString = "'" & String.Join("','", arayITEM) & "'"
    'MsgBox("HASIL : " & resultString)

这是屏幕截图

enter image description here

我不需要在最后一个数组的元素(,''

的末尾使用分隔符

2 个答案:

答案 0 :(得分:2)

Dim res as string = "SELECT ITEM FROM DETAIL WHERE TID='1'"
CMD = New MySqlCommand(res, con)


' Read data from database
Dim result As New ArrayList()
Dr = CMD.ExecuteReader()

' Add each entry to array list
While Dr.Read()
    ' Insert each column into a dictionary
    Dim dict As New Dictionary(Of String, Object)
    For count As Integer = 0 To (Dr.FieldCount - 1)
        dict.Add(Dr.GetName(count), Dr(count))
    Next

    ' Add the dictionary to the ArrayList
    result.Add(dict & ", ")
End While
Dr.Close()

所以,现在你可以用这样的for循环遍历结果:

For Each dat As Dictionary(Of String, Object) In result
     Console.Write(dat("ColName"))
Next

如果它只是DataReader,那么你会怎么做:

While Dr.Read()
    Console.Write(Dr("ColName"))
End While

代码来自:Reference 我已将其修改为您想要的,但未经测试。 希望可以帮到你。

答案 1 :(得分:1)

这个怎么样:

Dim res as string = "SELECT ITEM FROM DETAIL WHERE TID='1'"
CMD = New MySqlCommand(res, con)
result = CMD.ExecuteReader()
Dim resultString as String = ""
Dim isFirstResult = True
while result.HasRows
  result.Read()
  If Not isFirstResult Then 
    resultString &= string.Format(",'{0}'",result("ITEM"))
  Else 
    isFirstResult = False
    resultString &= string.Format("'{0}'",result("ITEM"))
  End If
end while

或者,如果您想继续使用数组但也需要单字符串版本,则可以使用String.Join转换数组:

Dim resultString As String = "'" & String.Join("','", array) & "'"

String.Join非常聪明,只有在下一个元素存在时才添加分隔符。因此,上述两种方法都应该产生相同的结果。