【问题标题】:Odbc to oleDb necessary changes in MS AccessMS Access 中 Odbc 到 oleDb 的必要更改
【发布时间】:2013-01-22 18:21:14
【问题描述】:

我在 .net 中有一个类来使用 Odbc 连接 Access,但我想升级到 OleDb

Odbc 代码是:

Imports System.Data.Odbc
Imports System

Public Class DatabaseFunctions
    Shared con As OdbcConnection

    Const conString = "Dsn=name;uid=sa;pwd=password;"

    Public Shared Function GetDataReader(ByVal SQL As String) As OdbcDataReader
        Dim dr As OdbcDataReader
        Try
            con = New OdbcConnection
            con.ConnectionString = conString
            con.Open()
            Dim cmd As New OdbcCommand(SQL, con)
            dr = cmd.ExecuteReader
            cmd.Connection.Close()
            cmd.Connection.Dispose()
            cmd.Connection = Nothing
            cmd.Parameters.Clear()
            cmd.Dispose()
            cmd = Nothing
            con.Close()
            con.Dispose()
            Return dr
        Catch ex As Exception
            MessageBox.Show("Error:" & ex.Message, "TITLE", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            If (con.State = System.Data.ConnectionState.Open) Then
                con.Close()
                con.Dispose()
            End If
        End Try
        dr = Nothing
        Return dr
    End Function

    Public Shared Function GetDataReaderVal(ByVal SQL As String) As String
        Dim result As String
        Try
            con = New OdbcConnection
            con.ConnectionString = conString
            con.Open()
            Dim cmd As New OdbcCommand(SQL, con)
            Dim dr As OdbcDataReader
            result = ""
            dr = cmd.ExecuteReader
            dr.Read()
            resultado = dr.GetValue(0).ToString
            cmd.Connection.Close()
            cmd.Connection.Dispose()
            cmd.Connection = Nothing
            cmd.Parameters.Clear()
            cmd.Dispose()
            cmd = Nothing
            con.Close()
            con.Dispose()
            Return resultado
        Catch ex As Exception
            MessageBox.Show("Error GETTING DATA:" & ex.Message, "TITLE", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            If (con.State = System.Data.ConnectionState.Open) Then
                con.Close()
                con.Dispose()
            End If
        End Try
        resultado = "0"
        Return resultado
    End Function


    Public Shared Function GetDataTable(ByVal SQL As String) As DataTable
        Dim table As New DataTable
        Try
            con = New OdbcConnection
            con.ConnectionString = conString
            con.Open()
            Dim cmd As New OdbcCommand(SQL, con)

            Dim da As New OdbcDataAdapter(cmd)
            da.Fill(table)
            cmd.Connection.Close()
            cmd.Connection.Dispose()
            cmd.Connection = Nothing
            cmd.Parameters.Clear()
            cmd.Dispose()
            cmd = Nothing
            con.Close()
            con.Dispose()
            Return table
        Catch ex As Exception
            MessageBox.Show("Error GETTING TABLE:" & ex.Message, "TITLE", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            If (con.State = System.Data.ConnectionState.Open) Then
                con.Close()
                con.Dispose()
            End If
        End Try
        Return table
    End Function



    Public Shared Sub ExecuteQuery(ByVal SQL As String)
        Try
            con = New OdbcConnection
            con.ConnectionString = conString
            con.Open()
            Dim cmd As New OdbcCommand(SQL, con)
            cmd.ExecuteNonQuery()
            cmd.Connection.Close()
            cmd.Connection.Dispose()
            cmd.Connection = Nothing
            cmd.Parameters.Clear()
            cmd.Dispose()
            cmd = Nothing
            con.Close()
            con.Dispose()
        Catch ex As Exception
            MessageBox.Show("Error EXE QUERY:" & ex.Message, "TITLE", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            If (con.State = System.Data.ConnectionState.Open) Then
                con.Close()
                con.Dispose()
            End If
        End Try
    End Sub
End Class

我在做:

Imports System.Data.OleDb

Public Class DatabaseFunctions

    Dim Provider As String
    Public OleCn As New OleDbConnection()
    Public OleDa As New OleDbDataAdapter()


    Public Shared Function OledbConnectionString() As String
        Provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Application.Info.DirectoryPath & "/dbFile.Accdb;Jet OLEDB:Database Password=password;"
        Return Provider
    End Function


    Public Shared Sub start()
        If OleCn.State <> ConnectionState.Open Then
            OleCn.ConnectionString = OledbConnectionString()
            OleCn.Open()
        End If
    End Sub

    Public Sub finish()
        OleCn.Close()
    End Sub

  Public Shared Sub ExecuteQuery(ByVal SQL As String)
        Dim OleDr As OleDbDataReader
        OleDa.SelectCommand = New OleDbCommand()
        OleDa.SelectCommand.CommandText = SQL 
        OleDa.SelectCommand.Connection = OleCn
        OleDr = OleDa.SelectCommand.ExecuteReader()     
        OleDr.Close()
  End Sub

End Class

如何像在 odbc 中一样返回一个表、一个值和读取器,我很困惑......

【问题讨论】:

  • 很难从哪里开始。您需要阅读 ADO.net 以及 SQl 和 C# 的最佳实践,但您不会遵循其中的任何一个。
  • 好吧,我使用的是 VB.NET,所以比我想象的要难
  • 这比你想象的要难,因为你在做 VB.notnet。给我一点,我会把一些 C# 代码翻译成 VB,告诉你在 .net 中以原始代码进行数据访问的正确方法

标签: .net vb.net visual-studio-2010 odbc oledb


【解决方案1】:

这个代码不错,看看吧:

Imports System.Data.SqlClient
Imports System.Data.Common
Imports System.IO

Public Class DbConn
    Private DataCon As DbConnection
    Private DBConnectionOpen As Boolean = False

    ''' <summary>
    ''' Submits a SQL query to an Access database
    ''' </summary>
    ''' <param name="sql">The SQL query</param>
    ''' <returns>A datatable (result set) containing the data requested by the query; returns Nothing if there is a SQL error.</returns>
    ''' <remarks>Use for SELECT queries; use ExecuteSQL for action queries.
    ''' This function does not permanently change whether the connection is open or not.
    ''' If the connection is already open, it gets the data and leaves it open.
    ''' If the connection is closed, it opens it, gets the data, and closes it again.</remarks>
    Public Function GetDataTable(ByVal sql As String) As DataTable
        Dim rsData As New DataTable()
        ' 
        Dim ConnectionWasAlreadyOpen As Boolean = DBConnectionOpen
        If Not ConnectionWasAlreadyOpen Then OpenDatabaseConnection()
        If DBConnectionOpen Then
            Dim cmd As DbCommand = DataCon.CreateCommand
            cmd.CommandType = CommandType.Text
            cmd.CommandText = sql
            Try
                Dim rdr As DbDataReader = cmd.ExecuteReader()
                rsData.Load(rdr, LoadOption.Upsert)
                rdr.Close()
                rdr = Nothing
            Catch ex As Exception
                Throw New System.Exception(ex.Message, ex)
                GetDataTable = Nothing
                Exit Function
            End Try
            GetDataTable = rsData
        Else
            GetDataTable = Nothing
        End If
        If Not ConnectionWasAlreadyOpen Then CloseDatabaseConnection()
    End Function

    ''' <summary>
    ''' Executes a SQL action query (INSERT, UPDATE, DELETE, CREATE, etc.)
    ''' </summary>
    ''' <param name="sql">The text of the SQL action query</param>
    ''' <remarks>Use for action queries; use GetDataTable for SELECT queries
    ''' This sub does not permanently change whether the connection is open or not.
    ''' If the connection is already open, it gets the data and leaves it open.
    ''' If the connection is closed, it opens it, gets the data, and closes it again.</remarks>
    Public Sub ExecuteSQL(ByVal sql As String)
        Dim ConnectionWasAlreadyOpen As Boolean = DBConnectionOpen
        If Not ConnectionWasAlreadyOpen Then OpenDatabaseConnection()
        If DBConnectionOpen Then
            Dim cmd As DbCommand = DataCon.CreateCommand
            cmd.CommandType = CommandType.Text
            cmd.CommandText = sql
            cmd.ExecuteNonQuery()
        End If
        If Not ConnectionWasAlreadyOpen Then CloseDatabaseConnection()
    End Sub


    ''' <summary>
    ''' Creates a new connection to an Access database
    ''' </summary>
    ''' <param name="FileName">The full path of the Access file</param>
    ''' <remarks></remarks>
    Public Sub New(ByVal FileName As String)
        'Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccess2007file.accdb;Persist Security Info=False;
        Dim fileData As FileInfo = My.Computer.FileSystem.GetFileInfo(FileName)
        DataCon = New OleDb.OleDbConnection
        Dim csb As OleDb.OleDbConnectionStringBuilder = New OleDb.OleDbConnectionStringBuilder
        csb.ConnectionString = "Data Source=" & FileName
        Select Case fileData.Extension.ToLower
            Case ".mdb" : csb.Add("Provider", "Microsoft.Jet.Oledb.4.0")
            Case ".accdb" : csb.Add("Provider", "Microsoft.ACE.OLEDB.12.0")
        End Select
        DataCon.ConnectionString = csb.ConnectionString
        Try
            DataCon.Open()
            DataCon.Close()
        Catch ex As Exception
            Throw New System.Exception("Unable to connect to database.", ex.InnerException)
        End Try
    End Sub

    ''' <summary>
    ''' Connects to a SQL Server database
    ''' </summary>
    ''' <param name="ServerName">SQL Server server</param>
    ''' <param name="DatabaseName">Default database</param>
    ''' <remarks></remarks>
    Public Sub New(ByVal ServerName As String, ByVal DatabaseName As String)
        DataCon = New SqlConnection()
        Dim csb As SqlConnectionStringBuilder = New SqlConnectionStringBuilder
        csb.DataSource = ServerName
        csb.InitialCatalog = DatabaseName
        csb.IntegratedSecurity = True
        csb.MultipleActiveResultSets = True
        DataCon.ConnectionString = csb.ConnectionString
        Try
            DataCon.Open()
            DataCon.Close()
        Catch ex As Exception
            Throw New System.Exception("Unable to connect to database.", ex.InnerException)
        End Try
    End Sub

    ''' <summary>
    ''' Makes certain that the database connection is closed when the object is destroyed
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overrides Sub finalize()
        Try
            DataCon.Close()
        Catch ex As Exception

        End Try
    End Sub

    ''' <summary>
    ''' Opens a database connection to an access file
    ''' </summary>
    ''' <remarks>Since the procedures in this module share the "DataCon" DbConnection, it is impossible to open multiple connections using these procedures.</remarks>
    Public Sub OpenDatabaseConnection()
        Try
            DataCon.Open()
        Catch ex As Exception
            Throw New System.Exception("Error opening data connection.", ex.InnerException)
            DBConnectionOpen = False
            Exit Sub
        End Try
        DBConnectionOpen = True
    End Sub

    ''' <summary>
    ''' Closes the DataCon DbConnection
    ''' </summary>
    ''' <remarks>Note that the GetDataTable and ExecuteSQL procedures leave (or return) the connection to its previous open/close state. To keep the connection open while running several queries, call OpenDatabaseConnection before the queries and CloseDatabaseConnection after. When running one query at a time, there is no need to explicitly call either function, because GetDataTable and ExecuteSQL will open and close the database if it was closed to begin with.</remarks>
    Public Sub CloseDatabaseConnection()
        DataCon.Close()
        DBConnectionOpen = False
    End Sub
End Class

【讨论】:

  • 不怕。除了引入巨大的 sql 注入攻击向量和同时无法运行参数化查询之外,它还忽略了 ADO.Net 的连接池。这是 VB.Net 代码,但不是 .net 方法。至少你没有吞下例外,否则我只好记下你了。
  • 在担心效率之前,您需要先做好准备。要做到这一点,你永远不允许 Execute(ByVal sql as String),在这种情况下,整个事情都在 bin 中。 GetOrders(CustomerID as Int) 是您应该做的,然后使用参数化查询来获取该客户的订单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多