You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用VB.NET向MS Access插入数据?插入后数据未显示求助

VB.NET插入Access数据库数据失败的解决办法

你的代码核心问题是:创建了命令对象但没有执行SQL插入语句——缺少command.ExecuteNonQuery()调用,数据库根本没收到插入指令,所以数据没存入。

修正后的代码

Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
    ' 使用Using语句自动管理连接和命令的资源释放,比手动Close更可靠
    Using con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Desktop\School\DBLC.accdb")
        Try
            con.Open()
            Dim query As String = "INSERT INTO LC ([Name of Applicant], [Address of Applicant], [Contact of Applicant]) VALUES (@NameApp, @AddressApp, @ContactApp)"
            
            Using command As New OleDbCommand(query, con)
                ' 显式指定参数类型,避免AddWithValue可能的类型匹配问题
                command.Parameters.Add("@NameApp", OleDbType.VarChar).Value = txtboxNameApp.Text
                command.Parameters.Add("@AddressApp", OleDbType.VarChar).Value = txtboxAddressApp.Text
                command.Parameters.Add("@ContactApp", OleDbType.VarChar).Value = txtboxContactApp.Text
                
                ' 执行插入语句,返回受影响的行数
                Dim affectedRows As Integer = command.ExecuteNonQuery()
                
                If affectedRows > 0 Then
                    MsgBox("新记录添加成功!")
                Else
                    MsgBox("记录添加失败,请检查输入或数据库配置")
                End If
            End Using
        Catch ex As Exception
            MsgBox($"错误信息:{ex.Message}")
        End Try
        ' Using块结束后会自动关闭连接,无需手动Close
    End Using
End Sub

初学者额外注意事项

  • 执行增、删、改这类非查询SQL语句,必须调用ExecuteNonQuery(),它的返回值是受影响的行数,可以用来验证操作是否成功
  • 优先使用Using语句管理数据库连接和命令对象,能自动释放资源,避免连接泄漏导致的数据库异常
  • 尽量避免直接用AddWithValue,显式指定参数类型(比如OleDbType.VarChar)可以避免数据类型不匹配的问题
  • 确保连接字符串里的数据库路径正确,比如C:\Users\Desktop\School\DBLC.accdb要确认文件存在、路径无拼写错误

内容的提问来源于stack exchange,提问作者Dovah Pixel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 00:21:08