ADO.NET跟VB6.0、VBA中的ADO变化较大。
在.NET中要使用ADO.NET,首先需要引用System. Data. Ole Db 命名空间。
在ADO.NET中,如果要连接某个数据源可以有多种方法。
方法一、使用Ole DbConnection 类。
比如要连接某个Access数据库文件,可以使用如下的代码段:
Imports ado = System.Data.OleDb
Module Module1
Sub QQ1722187970()
Dim sConstr As String
sConstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sFile & ";Persist Security Info=False;"
Dim oCon As New ado.OleDbConnection(sConstr)
oCon.Open()
End Sub
End Module
然后要返回查询结果,可以使用Ole DbCommand类,用该类的Execute Reader方法返回一个查询结果集OleDbDataReader类。
代码段如下:
Imports ado = System.Data.OleDb
Module Module1
Sub QQ1722187970()
Dim sConstr As String
sConstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sFile & ";Persist Security Info=False;"
Dim oCon As New ado.OleDbConnection(sConstr)
oCon.Open()
Dim sSQl As String
sSQl = "select * from 教师授课表"
Dim oCmd As New ado.OleDbCommand(sSQl, oCon)
Dim oReader As ado.OleDbDataReader = oCmd.ExecuteReader()
End Sub
End Module
最后读取OleDbDataReader,代码如下:
Imports lbForm = System.Windows.Forms
Imports ado = System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oOpenFileDialog As New lbForm.OpenFileDialog
Dim sFile As String
Dim arrFN()
With oOpenFileDialog
.ShowDialog()
sFile = .FileName
If Len(sFile) Then
Dim sConstr As String
sConstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sFile & ";Persist Security Info=False;"
Dim oCon As New ado.OleDbConnection(sConstr)
oCon.Open()
Dim sSQl As String
sSQl = "select * from 教师授课表"
Dim oCmd As New ado.OleDbCommand(sSQl, oCon)
Dim oReader As ado.OleDbDataReader = oCmd.ExecuteReader()
Dim iCol As Integer
With oReader
iCol = .FieldCount
'读取字段名
For I = 0 To iCol - 1
Dim sFieldName As String
sFieldName = .GetName(I)
ReDim Preserve arrFN(I)
arrFN(I) = sFieldName
Debug.Print(sFieldName)
Next
'逐条读取记录
Do Until .Read = False
For I = 0 To iCol - 1
Dim sValue As String
sValue = .Item(arrFN(I))
Debug.Print(sValue)
Next I
Loop
.Close()
End With
oCon.Close()
Else
MsgBox("你没有选择文件")
End If
End With
End Sub
End Class


发表评论