MS Access或SQL Server的代码

时间:2016-08-08 01:51:20

标签: sql-server ms-access

我有一个使用SQL Server数据库或MS Access数据库的程序。

我正试图找出一种方法来使用具有相同代码的任一数据库。作为一个例子,你可以根据你正在使用的数据库进行操作:

SQL Server:

Using cmd As SqlCommand = New SqlCommand(SQLQuery, Connection)
    Using rs As SqlDataReader = cmd.ExecuteReader
        Do While rs.Read
            ' Do something
        Loop
    End Using
End Using

MS Access:

Using cmd As OleDbCommand= New OleDbCommand(SQLQuery, Connection)
    Using rs As OleDbDataReader= cmd.ExecuteReader
        Do While rs.Read
            ' Do something
        Loop
    End Using
End Using

在我的情况下,我可以实现这样的事情:

Dim rs As New Object
Dim con As Object
Dim cmd As Object
If SQL-Server Then
    con = TryCast(conSQL-Server, SqlConnection)
    cmd = New SqlCommand
    rs = TryCast(rs, SqlDataReader)
Else
    con = TryCast(conMS-Access, OleDb.OleDbConnection)
    cmd = New OleDb.OleDbCommand
    rs = TryCast(rs, OleDb.OleDbDataReader)
End If   
Try
    With cmd
        .Connection = con
        .CommandText = SQLQuery
        rs = .ExecuteReader
    End With
    Do While rs.Read
        ' Do something
    Loop
Catch ex As Exception
    ' Handle Error        
Finally
    If Not rs Is Nothing Then
        If Not rs.IsClosed Then rs.Close()
        rs.Dispose()
    End If
    cmd.Dispose()
End Try

但这很麻烦。如果您可以创建自定义类型来执行以下操作,那将是很好的:

If SQL-Server Then
    DBCommand = SqlCommand
    DBReader = SqlDataReader
Else
    DBCommand = OleDbCommand
    DBReader = OleDbDataReader
End
Using cmd As DBCommand = New DBCommand(SQLQuery, connection)
    Using rs As DBReader = cmd.ExecuteReader
        Do While rs.Read
            ' Do something
        Loop
    End Using
End Using

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我发现了答案:

Dim con As IDbConnection
If SQL-Server Then
    con = conSQL-Server
Else
    con = conMS-Access
End If
Using cmd As IDbCommand = con.CreateCommand()
    cmd.CommandText = SQLQuery
    Using rs As IDataReader = cmd.ExecuteReader
        Do While rs.Read()
            ' Do something
        Loop       
    End Using
End Using

太糟糕了,CreateCommand不接受参数。