我正在使用Visual Studio 2015而我正在尝试创建一个模块,因此我的db2连接将是公开的。
它类似于登录程序。
这是我的登录号CODE1
Imports IBM.Data.DB2
Public Class LoginForm
Dim dbConn As Common.DbConnection
Private Sub BtnLogin_Click(sender As Object, e As EventArgs) Handles
BtnLogin.Click
Dim user As String
Dim pass As String
user = Me.txtUser.Text
pass = Me.txtPass.Text
dbConn = New DB2Connection("server = localhost; database = hotel;" + "uid = '" & user & "'; password='" & pass & "';")
dbConn.Open()
If dbConn.State = ConnectionState.Open Then
Try
Main_Menu_Form.Show()
Me.Hide()
Catch ex As Exception
MsgBox(e.ToString)
End Try
End If
End Sub
以及我在模块中写的内容(它不会起作用)CODE2
Module Module1
Public dbConn As Common.DbConnection
End Module
我希望连接可以在其他表单上使用。
这是我的CODE3
Private Sub BtnLogin_Click(sender As Object, e As EventArgs) Handles BtnLogin.Click
If dbConn.State = ConnectionState.Open Then
Try
Dim str As String = "select * from table(EMPLOYEEDISP(20)) as udf"
Dim cmd As DB2Command = New DB2Command(str, dbConn)
Dim rdr As DB2DataReader
rdr = cmd.ExecuteReader
DGVEx.ColumnCount = 5
DGVEx.Columns(0).Name = "Employee Number"
DGVEx.Columns(1).Name = "Name"
DGVEx.Columns(2).Name = "Position"
DGVEx.Columns(3).Name = "Username"
DGVEx.Columns(4).Name = "Password"
Dim row As String()
While rdr.Read()
row = New String() {rdr.GetString(0), rdr.GetString(1), rdr.GetString(2), rdr.GetString(3), rdr.GetString(4)}
DGVEx.Rows.Add(row)
End While
MsgBox("Executed")
Catch ex As Exception
MsgBox(e.ToString)
End Try
End If
End Sub
这是我从CODE3得到的错误
未处理的类型' System.NullReferenceException'发生在Hotel.exe
附加信息:未将对象引用设置为对象的实例。
这可能是因为dbConn.State
未关闭或未连接,我认为CODE2(模块)存在问题。
在模块中公开连接的正确代码是什么?
答案 0 :(得分:0)
在CODE3中,您需要初始化dbConn
。会发生什么是您尝试访问未初始化对象的属性 - NullReferenceExeption
的含义。所以就像你在CODE1中那样做:
dbConn = New DB2Connection("server = localhost; database = hotel;" + "uid = '" & user & "'; password='" & pass & "';")
现在您可以查看State
属性
但是,我不推荐这种方法,特别是如果这是WEB应用程序。
使用实际需要的连接对象并妥善处理它。最有效的方法是通过Using
声明:
Using dbConn = New DB2Connection("server = localhost; database = hotel;" + "uid = '" & user & "'; password='" & pass & "';")
' Do your stuff...
End Using
现在您可以确定已放置dbConn
并且没有内存泄漏。