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

VB.NET中System.NullReferenceException异常求助:对象未实例化

问题排查与解决

异常原因

你遇到的System.NullReferenceException是因为代码中声明的ADODB.Connection和ADODB.RecordSet对象仅完成了变量声明,未创建实际的对象实例,直接调用它们的Open方法时,变量指向的是Nothing(空引用),因此触发异常。

解决步骤

1. 实例化数据库连接与记录集对象

在调用Open方法前,必须用New关键字创建对象实例:

public database as ADODB.Connection
public table as ADODB.RecordSet
Private Sub frmSales_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' 实例化Connection对象
        database = New ADODB.Connection()
        database.Open("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Windows10\Downloads\FinalsProject.accdb")
        
        ' 实例化RecordSet对象
        table = New ADODB.RecordSet()
        table.Open("select * from TB_Transactions", database, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockOptimistic)
        table.MoveFirst()

        Call DisplayRecord()
        Call DisabledControl()
 End Sub

2. 补充资源释放逻辑(可选但推荐)

为避免数据库连接泄漏,建议在窗体关闭时关闭并释放对象:

Private Sub frmSales_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
    ' 关闭记录集
    If Not table Is Nothing AndAlso table.State = ADODB.ObjectStateEnum.adStateOpen Then
        table.Close()
        table = Nothing
    End If
    ' 关闭数据库连接
    If Not database Is Nothing AndAlso database.State = ADODB.ObjectStateEnum.adStateOpen Then
        database.Close()
        database = Nothing
    End If
End Sub

3. 额外检查项

  • 确认数据库文件路径C:\Users\Windows10\Downloads\FinalsProject.accdb真实存在,且程序有读取该文件的权限
  • 确认项目已正确引用Microsoft ActiveX Data Objects x.x Library组件(在项目引用中添加)

内容的提问来源于stack exchange,提问作者ouie raphael

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 21:01:40