如何使用vb 2010从访问数据库中获取和显示数据

时间:2015-05-06 07:30:39

标签: vb.net visual-studio-2010

我刚接触vb 2010并且正在尝试从访问数据库(Employees.mdb)中获取数据,但我现在正在堆栈如何显示数据,任何人都有帮助。感谢

Public Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim LoginUser As String
    LoginUser = LoginForm.TextBoxID.Text ' User Login Name
    DisplayLogin.Text = LoginUser ' Display now user to form

    Dim db As String = "Employees.mdb"

    Dim DatabasePath As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\QBook Api\data api\" + db
    If My.Computer.FileSystem.FileExists(DatabasePath) Then
        Dim con As New OleDb.OleDbConnection
        Dim cmd As New OleDb.OleDbCommand
        Dim Sql As String
        Dim NumOfRows As Integer
        Dim TodayDate As String = Today
        con.ConnectionString = "PROVIDER = Microsoft.Jet.OLEDB.4.0; Data Source = " + DatabasePath

        con.Open() ' Opening oLe Connection

        ' Checking database if we have todays or Searched records
        Sql = "SELECT * FROM Employees INNER JOIN TimeTable ON Employees.EmployeeNo = TimeTable.RefID WHERE Dated = '" & TodayDate & "' "
        cmd = New OleDb.OleDbCommand(Sql, con)
        NumOfRows = cmd.ExecuteScalar()
        cmd.ExecuteNonQuery()
        If NumOfRows > 0 Then
            ' Here I need to display the data


        Else
            MsgBox("Sorry we don’t have Entry Logs of (" + TodayDate + ")", MsgBoxStyle.Critical, Title:="QBook - No entry found")
        End If
        con.Close() ' Closing Connection
    Else

        MsgBox("Unable to get database file in (" + DatabasePath + ")", MsgBoxStyle.Critical)

    End If ' no database found




End Sub

任何建议都表示赞赏和欢迎

1 个答案:

答案 0 :(得分:0)

ExecuteScalar仅返回结果集中第一行的第一列,因此您无法显示除此之外的任何数据。如果您获得计数,总和或仅返回一个值的内容,通常会使用它。

如果您想要阅读和显示数据,请改用ExecuteReaderhttps://msdn.microsoft.com/en-us/library/979byfca(v=vs.110).aspx)。然后,您可以使用它将结果绑定到DataGridView之类的内容。

Dim reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)

If reader.HasRows() Then
    Dim dt = New DataTable()
    dt.Load(reader)
    dataGridView2.DataSource = dt
Else
    'No log entries to display
End If