最近在学习VB,在建立数据库连接的实例上出现异常,求大神点拨~~~谢过了
代码如下:
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Cstring As String = "provider = Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ZX\Desktop\OnLineSystemDB.accdb"
Dim SqlStr As String = "Select 数据编号,日期,测点名称 From VibrationData where 测点名称 = 'BA'"
Dim strRow As String = ""
Dim myCon As New OleDbConnection(Cstring)
Try
myCon.Open()
MessageBox.Show("已正确建立连接", "连接正确对话框")
myCon.Close()
Catch ex As OleDbException
MessageBox.Show(ex.Message, "连接失败对话框")
Exit Sub
End Try
Dim myCom As New OleDbCommand()
myCom.Connection = myCon
myCom.CommandType = CommandType.Text
myCom.CommandText = SqlStr
Dim myDataReader As OleDbDataReader = myCom.ExecuteReader()
Label1.Text = ""
Do While (myDataReader.Read())
strRow = myDataReader.GetString(0) + " "
strRow += myDataReader.GetString(1) + " "
strRow += myDataReader.GetString(2) + " "
Label1.Text = Label1.Text + strRow + Chr(20) + Chr(20)
Loop
myDataReader.Close()
myCon.Close()
End Sub
End Class
------解决方案--------------------
try里mycon被你close掉了……
------解决方案--------------------
MessageBox.Show("已正确建立连接", "连接正确对话框")
myCon.Close() <===这句去掉
------解决方案--------------------
你把数据库的连接关掉了,肯定会报错,要重新建立连接或者使用完后再关闭连接...