无法使用vb.net连接到访问数据库

时间:2016-04-20 03:24:01

标签: vb.net

我正在尝试连接到我的访问数据库,这是mdb到vb.net项目。我已经将平台更改为x86但它仍然无法正常工作。我似乎真的不知道问题是什么。希望我能得到一些帮助,谢谢你提前

Imports System.Data.OleDb 'provides classes to connect to the database

Public Class Form1
Dim conn As New OleDbConnection

Private Sub RefreshData()
    If Not conn.State = ConnectionState.Open Then
        conn.Open()
    End If

    Dim da As New OleDbDataAdapter("SELECT ID as [No], " & _
                                   "UserName as [Name], " & _
                                   "FROM Table1 " & _
                                   "ORDER BY ID", conn)
    Dim dt As New DataTable
    'fill data to dataTable
    da.Fill(dt)

    'Offer data in dataTable to dataGridView
    Me.DataGridView1.DataSource = dt

    'close connection
    conn.Close()
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    conn = New OleDbConnection
    conn.ConnectionString = "PROVIDER = Microsoft.Jet.OleDB.4.0; Data Source= C:\Users\user\Documents\Access Database\Database2.mdb"

    RefreshData()
End Sub
End Class

1 个答案:

答案 0 :(得分:0)

您的SQL语句中有错误。代码:

Dim da As New OleDbDataAdapter("SELECT ID as [No], " & _
    "UserName as [Name], " & _
    "FROM Table1 " & _
    "ORDER BY ID", conn)

NOT as [Name],之后是否应该使用逗号 相反它应该是:

Dim da As New OleDbDataAdapter("SELECT ID as [No], " & _
    "UserName as [Name] " & _ `NO COMMA!
    "FROM Table1 " & _
    "ORDER BY ID", conn)