我刚开始弄乱Visual Basic(vb.net),并试图在TextBox中显示多于1个数据库行,到目前为止,我有这个:
Private Sub foobox_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = connStr
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("No connection")
End Try
Dim myAdaptor As New MySqlDataAdapter
Dim sqlquery = "SELECT * FROM foo ORDER BY id DESC"
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sqlquery
myAdaptor.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
If myData.HasRows Then
myData.Read()
Viewer.Text = myData("foo1") & myData("foo2")
End If
myData.Close()
conn.Close()
End Sub
哪个成功连接到数据库,但只输出1行,如何获取更多行呢?
最佳答案
您需要一个循环读取数据并在StringBuilder中逐行存储。
然后,从阅读循环退出时,设置文本框的Text属性
Dim sb as StringBuilder = new StringBuilder()
While myData.Read()
sb.AppendLine(myData("foo1") & myData("foo2"))
End While
Viewer.Text = sb.ToString
并且,当然,您的文本框应将
MultiLine
属性设置为True除了直接回答您的问题之外,还应在使用后更改您的代码以处理连接和数据读取器,我也删除了DataAdapter,因为这里不需要
Using conn = New MySqlConnection(connStr)
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("No connection")
End Try
Dim sqlquery = "SELECT * FROM foo ORDER BY id DESC"
Dim myCommand As New SqlCommand(sqlquery, conn)
Using myData = myCommand.ExecuteReader()
Dim sb as StringBuilder = new StringBuilder()
While myData.Read()
sb.AppendLine(myData("foo1") & myData("foo2"))
End While
Viewer.Text = sb.ToString
End Using
End Using