显示数据库中的多个数据,并将其显示在一个文本框中

时间:2018-04-19 16:15:40

标签: sql vb.net sorting ms-access

我正在制作游戏,并想在一个文本框中显示所有学生的结果(或者无论如何都可以显示它)

在我的数据库中,我有一个名为username的字段。每次游戏结束时,这会将相同的用户名添加为新记录,其中也包含分数。问题是,我似乎只能显示最新的分数。我如何在一个盒子中显示一名学生的所有结果。另外,我如何用逗号分隔它们?谢谢

Imports System.Data.OleDb
' Accesses my database, and checks whether the teacher is in the database '
Public Class RetrieveResults
    Dim provider As String
    Dim dataFile As String
    Dim connString As String
    Public myConnection As OleDbConnection = New OleDbConnection
    Public dr As OleDbDataReader
    Private Sub Retrieveresults_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
        dataFile = "D:\Student Database1.accdb"
        connString = provider & dataFile
        myConnection.ConnectionString = connString
    End Sub

Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    myConnection.Open()
    surname.Clear()
    Classs.Clear()
    Score.Clear()
    Dim str As String
    str = "SELECT * FROM [SCORE] WHERE (Student_UserName = '" & Student_name.Text & "')"
    Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
    dr = cmd.ExecuteReader
    While dr.Read()
        surname.Text = dr("Student_Username").ToString
        Classs.Text = dr("class").ToString
        Score.Text = dr("score").ToString
    End While
    myConnection.Close()
End Sub

End Class

1 个答案:

答案 0 :(得分:0)

Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            surname.Clear()
            Classs.Clear()
            Score.Clear()
            Dim str As String = "SELECT * FROM [SCORE] WHERE (Student_UserName = @StudentName);"
            Using myConnection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =D:\Student Database1.accdb")
                Using cmd As OleDbCommand = New OleDbCommand(str, myConnection)
                    cmd.Parameters.Add("@StudentName", OleDbType.VarChar).Value = Student_name.Text
                    myConnection.Open()
                    Using dr As OleDbDataReader = cmd.ExecuteReader
                        While dr.Read()
                            Classs.Text &= dr("class").ToString & ", "
                            Score.Text &= dr("score").ToString & ", "
                        End While
                    End Using
                End Using
            End Using
            surName.Text = Student_name.Text
End Sub
  1. 我直接在Connection构造函数中传递了连接字符串,而不是所有字符串。我将表单级别变量移动到按钮事件。
  2. 我在Connection,Command和DataReader上使用了Using ... End Using语句,以确保即使出现错误也能正确处理它们。
  3. 我将Select语句更改为使用参数。只要按照与S​​QL语句中相同的顺序添加参数,Access就不关心您所谓的内容。这里不是问题,因为只有一个。
  4. 我把surName从Whiile循环中取出来,应该只有一个值。
  5. 我添加了&在等号之前,循环将向文本框添加下一个值,并在每次迭代中添加逗号 我希望这有帮助。