vb.net 打开连接时未处理 NullReferenceException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13453035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NullReferenceException was unhandled when opening a connection
提问by Rara Arar
I'm getting an error in this code that says: object reference not set to an instance of an object.
我在这段代码中收到一条错误消息:object reference not set to an instance of an object。
Private Sub frmAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = strcon
con.Open()
con.ConnectionString = strcon
How can I fix this error?
我该如何解决这个错误?
回答by Steven Doggart
That means that you are using a variable that is null (it's not set to point to an instance of any object). In this case, conmust be null, so you need to check if it's null, and if so, then set it to a new object. For instance:
这意味着您正在使用一个 null 变量(它没有设置为指向任何对象的实例)。在这种情况下,con必须为空,所以你需要检查它是否为空,如果是,则将其设置为一个新对象。例如:
If con Is Nothing Then
con = New OleDbConnection() ' Or whatever type it is...
End If
con.ConnectionString = strcon
con.Open()
Or, better yet, just set it to a new object when you declare the variable, if that's appropriate, for instance:
或者,更好的是,只需在声明变量时将其设置为一个新对象,如果合适的话,例如:
Dim conn As New OleDbConnection()
However, as Tim pointed out, it's best to create a new connection each time you need one, and then you can use a Usingblock which will properly dispose of the object every time:
但是,正如 Tim 所指出的,最好在每次需要时创建一个新连接,然后您可以使用一个Using每次都正确处理对象的块:
Using con As New OleDbConnection(strcon)
con.Open()
' Use the connection ...
End Using
回答by Tim Schmelter
I assume that you get that error because the connection is yet not initialized. But instead of using a field i would suggest to create a local variable because you should always close connections as soon as possible best by using Using-statement. So create a connection where you need it and not globally.
我假设您收到该错误是因为连接尚未初始化。但是我建议不要使用字段,而是建议创建一个局部变量,因为您应该始终使用Using-statement尽快关闭连接。因此,在您需要的地方而不是全局创建一个连接。
So this would fix it(but is not recommended):
所以这可以解决它(但不推荐):
Private Sub frmAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con = new SqlConnection(strcon)
con.Open() ' <-- don't do that with connection pooling

