我的连接字符串可能会出现什么问题。它报告cnn未声明。
Dim cnn As New OleDbConnection
If rdbtnNewDbase.Checked = True Then
Dim cnn As new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=false; Data Source=..\HCHPClosedIn11.mdb")
ElseIf rdbtnOldDbase.Checked = True Then
Dim cnn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=false; Data Source=..\HCHPold.mdb")
End If
答案 0 :(得分:5)
您尝试在If/End If
范围内重新声明您的连接对象。实际上,您的代码甚至无法编译。此外,变量不能在声明范围之外使用。
你真正想做的是:
Dim cnn As OleDbConnection
If rdbtnNewDbase.Checked = True Then
cnn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=false; Data Source=..\HCHPClosedIn11.mdb")
ElseIf rdbtnOldDbase.Checked = True Then
cnn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=false; Data Source=..\HCHPold.mdb")
End If
或者,让它更短更清晰:
Dim cs As String =
"Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=false; Data Source=..\" &
If(rdbtnNewDbase.Checked, "HCHPClosedIn11.mdb", "HCHPold.mdb")
Dim cnn As New OleDbConnection(cs)
答案 1 :(得分:1)
试试这个:
Using cnn As New OleDbConnection(string.Format(
"Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=false; Data Source=..\{0}",
If(rdbtnNewDbase.Checked, "HCHPClosedIn11.mdb", "HCHPHold.mdb" ))
'...
End Using