如何从数据库中检索多个行

时间:2013-04-11 17:21:06

标签: mysql vb.net

好的,所以我创建了一个新项目,允许用户互相发送消息。我差不多完成了,只需要清理一些东西。

我已成功允许用户发送消息(通过mysql)。现在我在我应该检索消息并在表单中显示它的部分;这是我卡住的地方。如果用户在数据库中只有一条消息,那么很容易做到,但如果他有超过1条消息怎么办?我将如何检索它们并在表单中显示它们。我正在使用此查询:

SELECT ToID
FROM Message
WHERE (ID LIKE @ID)

它的作用是检查数据库中是否包含收件人的任何消息作为用户的ID。如果数据库确实包含任何消息,则程序将在文本框中显示它们。但是如果超过1条消息,数据库将如何在表单中显示它们?表单包含以下文本框:

  1. 发件人
  2. 主题
  3. 日期。
  4. 这是我希望用于检索邮件的查询:

    SELECT ID, Title, Body, Date, FromUsername
    FROM Message
    WHERE (ID LIKE @ID)
    

    请帮帮忙?任何其他解决方案都很好,只要它易于理解(我对vb不熟悉)。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,为什么不使用列表框而不是文本框来显示消息。这样,无论有多少消息,它们都会不断添加到列表框中。

类似的东西:

For Each s as String in messageList
listbox1.items.add(s)

Next

修改

检索数据然后将其绑定到列表框 - 我从未真正使用过mysql,所以我从谷歌搜索中解除了代码 - 它应该让你开始。

dim table as new DataTable("table1")

' Create a Connection
using conn as new MysqlConnection("...connectionstring")
    conn.Open() ' Open it

    ' Create a new Command Object
    using cmd as new MysqlCommand("SELECT ID, Title, Body, Date, FromUsername FROM Message WHERE (ID LIKE @ID)", conn)

        ' Create a DataAdapter
        ' A DataAdapter can fill a DataSet or DataTable
        ' and if you use it with a CommandBuilder it also
        ' can persist the changes back to the DB with da.Update(...)
        using da as new MysqlDataAdapter(cmd)
            da.Fill(table) ' Fill the table
        end using

    end using
end using

' A Binding Source allows record navigation
dim bs as new BindingSource(table, nothing)

' You can bind virtually every property (most common are "text" "checked" or "visible"
' of a windows.forms control to a DataSource
' like a DataTable or even plain objects



ListBox1.DisplayMember = "Message"
ListBox1.ValueMember = "ID"
ListBox1.DataSource = table2