通过Visual Basic窗体向Access数据库添加数据

时间:2013-09-19 19:25:31

标签: database visual-studio vba ms-access-2007

我有一个论坛,我希望用户输入个人资料名称,然后点击添加,然后它会在文本框中添加他们在我的表格中的ProfileName字段中输入的内容。当我单击“添加”按钮时,会出现一个错误,指出system.data.dll中发生了System.Data.OleDb.OleDbException类型的未处理异常。这是我的代码:

Private Sub RefreshData()
    Dim cnn As New OleDb.OleDbConnection
    If Not cnn.State = ConnectionState.Open Then
        cnn.Open()
    End If
    Dim da As New OleDb.OleDbDataAdapter("SELECT id AS [ID], " & _
        "ProfileName AS [Name] " & _
        " FROM Profile ORDER BY id", cnn)
    Dim dt As New DataTable
    da.Fill(dt)
    cnn.Close()
    Me.dgvData.DataSource = dt
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)                 Handles Button1.Click
    If (TextBox1.Text = "") Then
        MsgBox("Please enter a profile name.")
    Else
        Dim cnn As New OleDb.OleDbConnection("Provider=Microsof… Source=c:\Data\Database.mdb     ;Extended Properties=Paradox 5.x;")
        Dim cmd As New OleDb.OleDbCommand
        If Not cnn.State = ConnectionState.Open Then
            cnn.Open()
        End If

        cmd.Connection = cnn
        cmd.CommandText = "INSERT INTO Profile(ProfileName) " & _
            "VALUES (" & Me.TextBox1.Text & "')"
        cmd.ExecuteNonQuery()

        cnn.Close()
        Dim oForm As addsnake
        oForm = New addsnake
        oForm.Show()
        oForm = Nothing
        Me.Close()
    End If
End Sub

1 个答案:

答案 0 :(得分:1)

如果没有进一步的信息,我建议:

您无需为ID提供别名:

SELECT id AS [ID]

如果你愿意的话,你仍然可以将它括在方括号中:

SELECT [id]

您在以下行中缺少撇号:

"VALUES (" & Me.TextBox1.Text & "')"

同时检查connectionstrings.com

上的连接字符串