我刚刚开始使用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行,如何才能输出更多?
答案 0 :(得分:2)
您需要循环读取数据并在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
除了直接回答您的问题之外,您的代码应该更改为在使用后处理连接和datareader,我也删除了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
答案 1 :(得分:1)
你需要某种循环。我还会使用Using
语句来确保即使在异常的情况下也会处理所有非托管资源(它也会关闭连接):
Using conn As New MySqlConnection(connStr)
Using myCommand As New MySqlCommand("SELECT * FROM foo ORDER BY id DESC", conn)
Try
conn.Open()
Using myData = myCommand.ExecuteReader()
If myData.HasRows Then
While myData.Read()
Dim line = String.Format("{0}{1}{2}",
myData.GetString(myData.GetOrdinal("foo1")),
myData.GetString(myData.GetOrdinal("foo1")),
Environment.NewLine)
viewer.Text &= line
End While
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Using
End Using
但是,如果您想要显示多条记录,我建议使用ListBox
。它对许多项目更有效,并且它们也将它们彼此逻辑分开。
(只需将viewer.Text &= line
替换为ListBox1.Items.Add(line)
)