0

我有一个类似的查询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)

这是屏幕截图

在此处输入图像描述

我不需要在最后一个数组元素(,'')末尾的分隔符

4

2 回答 2

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

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

于 2014-01-25T08:54:19.630 回答
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只有在下一个元素存在时才添加分隔符。因此,上述两种方法都应该产生相同的结果。

于 2014-01-25T07:36:32.203 回答