简体   繁体   English

VB.NET/MS ACCESS 显示查询数据

[英]VB.NET/MS ACCESS Display data from query

I have a textbox that I need to run this query when the value changes for the textbox.我有一个文本框,当文本框的值更改时,我需要运行此查询。

Private Sub tbStudentID2_TextChanged(sender As Object, e As EventArgs) Handles tbStudentID2.TextChanged
    mySql = "SELECT DateDiff('d', [DateofRank], [currentDate]) FROM StudentData"
    ConnDB()
    myCommand = New OleDbCommand(mySql, myConnection)
    myCommand.ExecuteNonQuery()
    myRead = myCommand.ExecuteReader
    Do While myRead.Read = True
        tbDays.Text = myRead(0).ToString()
    Loop
End Sub

86 is display no matter which record I choose.无论我选择哪个记录,都显示86。 I think it is just retrieving the first record in the in the table.我认为它只是检索表中的第一条记录。

I want to display the number of days since a student has tested by subtracting DateofRank from currentDate.我想通过从 currentDate 中减去 DateofRank 来显示自学生测试以来的天数。 I am open to other ideas on how to achieve this.我对如何实现这一目标的其他想法持开放态度。

You're overwriting the value of the TextBox with each pass.每次传递都会覆盖 TextBox 的值。 Make sure Multiline is set to true and try the following.确保 Multiline 设置为 true 并尝试以下操作。

Dim builder As New StringBuilder
Do While myRead.Read = True
    'tbDays.Text &= myRead(0).ToString()  Note the &= to keep concatenating the string.
    builder.Append(myRead(0).ToString())
Loop
tbDays.Text = builder.ToString()

I think you just need to introduce a condition ~ WHERE ID = tbStudentID2.Text我觉得你只需要引入一个条件~ WHERE ID = tbStudentID2.Text

Private Sub tbStudentID2_TextChanged(sender As Object, e As EventArgs) Handles tbStudentID2.TextChanged
    Dim id As Integer
    If Integer.TryParse(tbStudentID2.Text, id) Then
        mySql = $"SELECT DateDiff('d', [DateofRank], [currentDate]) FROM StudentData WHERE id={id}"
        ConnDB()
        myCommand = New OleDbCommand(mySql, myConnection)
        myCommand.ExecuteNonQuery()
        myRead = myCommand.ExecuteReader()
        Do While myRead.Read()
            tbDays.Text = myRead(0).ToString()
        Loop
    End If
End Sub

I guess your ID is an Integer.我猜你的 ID 是一个整数。 If that's the case, this will work, and is immune to SQL injection.如果是这种情况,这将起作用,并且不受 SQL 注入的影响。 I validated your input.我验证了您的输入。 Do you want to query when a typo happens?您想在出现错字时查询吗? Also, do you really want to query, when typing 12345, ID=1, ID=12, ID=123, ID=1234, and ID=12345?另外,你真的要查询,在输入12345、ID=1、ID=12、ID=123、ID=1234、ID=12345时? Maybe it's not typed in - then it's OK.也许它没有输入 - 那么没关系。

You may need to change the condition to the appropriate field name ie [StudentData].[ID] ?您可能需要将条件更改为适当的字段名称,即[StudentData].[ID]

Also, this will always result in the last match in the table.此外,这将始终导致表格中的最后一场比赛。 If you don't expect more than one match, then you can just take the first.如果您不期望多于一场比赛,那么您可以选择第一场。 You could eliminate the Do While loop.您可以消除Do While循环。

I see some other issues such as disposable objects not being disposed.我看到了一些其他问题,例如未处理一次性物品。 You shouldn't keep your database connection open when you aren't using it.当您不使用它时,您不应该保持数据库连接打开。 The objects which should be disposed of immediately, in order, are myRead , myCommand , and myConnection .应该立即处理的对象依次是myReadmyCommandmyConnection This is easily handled by declaring them with the Using keyword, in the reverse order of my list.这可以通过Using关键字以与我的列表相反的顺序声明它们来轻松处理。 ConnDB() could return your connection in that case.在这种情况下, ConnDB()可以返回您的连接。

This is how I fixed with help from a post on an another site.这就是我在另一个网站上的帖子的帮助下修复的方法。 I do have one question though.不过我确实有一个问题。 If I comment out the first db connection - ConnDB() I get an error.如果我注释掉第一个数据库连接 - ConnDB() 我得到一个错误。 Why does it need two connection to work?为什么需要两个连接才能工作? It makes a connection in the using command.它在 using 命令中建立连接。 I had setup a data table from a class I wrote to make a connection and set it up so I declare Private Access As New DBControl at the top and I can add parameters and do my additions and edits that way.我已经从我编写的一个类中设置了一个数据表来建立连接并进行设置,因此我在顶部声明了 Private Access As New DBControl,我可以添加参数并以这种方式进行添加和编辑。 I didn't know how to make that work with the existing connection to the Access DBControl so I just did another connection.我不知道如何使用到 Access DBControl 的现有连接来实现这一点,所以我只是做了另一个连接。 Not the best but I am a beginner and don't know how to do things with more efficiency yet.不是最好的,但我是初学者,还不知道如何更有效地做事。

Private Sub tbStudentID2_TextChanged(sender As Object, e As EventArgs) Handles tbStudentID2.TextChanged
    mySql = "SELECT DateDiff('d', [DateofRank], [currentDate]) FROM StudentData"
    '"SELECT DateDiff('d', [DateofRank], [currentDate]) FROM StudentData WHERE id={id}"
    ConnDB()
    'myCommand = New OleDbCommand(mySql, myConnection)
    'myCommand.ExecuteNonQuery()

    Dim studentID As Integer
    If Not Integer.TryParse(tbStudentID2.Text, studentID) Then
        ' Not a valid ID
        tbDays.Text = String.Empty
    Else
        Using command As New OleDbCommand("SELECT DateDiff('d', [DateofRank], [currentDate]) FROM StudentData WHERE StudentID = @StudentID", myConnection)
            command.Parameters.AddWithValue("@StudentID", studentID)

            ConnDB()

            Dim days As Object = command.ExecuteScalar()
            tbDays.Text = If(Convert.IsDBNull(days), String.Empty, Convert.ToString(days))
        End Using


        ' ADD PARAMETERS - ORDER MATTERS !!!
        Access.AddParam("@TIG", tbDays.Text)
        Access.AddParam("@SID", tbStudentID2.Text)

        ' RUN COMMAND
        Access.ExecQuery("UPDATE StudentData " &
                         "SET TimeinGrade=@TIG " &
                         "WHERE StudentID=@SID")

        ' REPORT & ABORT ON ERRORS
        If NoErrors(True) = False Then Exit Sub
    End If
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM