OleDbDataAdapter Fill 和 OleDbDataReader 需要 3-5 分钟来填充

2024-02-19

这是一个非常奇怪的问题,因为它只发生在随机的全新 Windows 10 电脑上。填充数据适配器或数据读取器需要 1-5 分钟。这是从 Windows 7 旧电脑升级到全新 Windows 10 电脑时发生的第三台电脑。第一次出现是在一年前,问题只出现了1天。第二次我们无法修复它,只是将它们放回旧的 Windows 7 电脑上。现在又发生了。我们已经用相同型号的 Nuc 10i7 计算机替换了另外 4 台运行该程序的计算机,它们工作得很好,只需要 1-5 秒即可完成所有例程。

我不认为这是连接字符串或 SQL 语句,因为它在其他电脑上工作正常。

我将延迟隔离到 OleDbDataAdapter 或 OleDbDataReader 被填充时,这在下面的屏幕截图中在填充之前和之后使用日志记录功能很明显。

这是在 Nuc10i7 电脑上,VB.Net 程序从 Access 数据库调用一行数据。

Public Sub PrintSwatLoad(SwatKey As String)
    didPrint = True
    Try
        Dim sBarcode As String = ""
        Dim cn As New OleDbConnection(MDBConnect)
        Dim sSql As String = "" &
          "SELECT WeightCert, [SwatLog].[SwatDate], TareDate, SaleCode, " &
                "Species, Qual, SaleDesc, Trucker, TruckNo, TruckState, " &
                "TruckLic, TrlState, TrlLic, TruckType, Comments, TareLoad, " &
                "ScaleLoad, LoadNo, Logger, LogMethod, Block, Val(Gross) as GrossWt, " &
                "Val(Tare) as TareWt, Weight, PrintAvg, Brand, Commodity, SortCode, " &
                "Deck, UserInfo1, UserInfo2, EmergencyLevel, ReprintCount, " &
                "Reason, LocationName, Addr1, Addr2, OwnerName, LoggerName," &
                "Contract, Weighmaster, TT, Reprint, TareoutBarcode, PrintTare, TruckName, " &
                "ManualWeight, DeputyName, CertStatus, ReplacedCert  " &
          "FROM Swatlog INNER JOIN tblTempCert " &
            "ON [SwatLog].[SwatDate] = [tblTempCert].[SwatDate] " &
         "WHERE [tblTempCert].[SwatDate] = #" & SwatKey & "#"


        cn.Open()
        Dim cmd As New OleDbCommand(sSql, cn)
        'Dim da As New OleDbDataAdapter(cmd)
        'Dim ds As New DataSet
        Dim dt As New DataTable

        ''''''''right here is where it hangs'''''''''''''''''''
        Dim myreader As OleDbDataReader = cmd.ExecuteReader()
        ''''''''above this is where it hangs. deleted all my logging methods for clarity''''''''''
        '''
        While myreader.Read()
            If myreader.HasRows = True Then     'ds.Tables(0).Rows.Count
                'Dim WrkRow As DataRow = dt.Rows(0)    'ds.Tables(0).Rows(0)
                If IsTareout = True Then
                    sBarcode = Trim(myreader("Trucker")) & myreader("TruckNo")
                End If

                Dim rSwatLaserCert As New XRSwatLaserCert
                rSwatLaserCert.DataSource = dt
                Dim rpt As New DevExpress.XtraReports.UI.ReportPrintTool(rSwatLaserCert)
                With rSwatLaserCert
                    .XrBCTareOut.Text = sBarcode
                    If Not (myreader("ManualWeight") = 1 Or myreader("ManualWeight") = 3) Then
                        .XrLabelManualGross1.Visible = False
                        .XrLabelManualGross2.Visible = False
                        .XrLabelManualGross3.Visible = False
                    End If

                    If Not (myreader("ManualWeight") = 2 Or myreader("ManualWeight") = 3) Then
                        .XrLabelManualTare1.Visible = False
                        .XrLabelManualTare2.Visible = False
                        .XrLabelManualTare3.Visible = False
                    End If

                    If myreader("CertStatus") = 1 Then
                    ElseIf myreader("CertStatus") = 2 Then
                        .XrLabelCertStatus1.Text = "VOID"
                        .XrLabelCertStatus2.Text = "VOID"
                        .XrLabelCertStatus3.Text = "VOID"
                    Else
                        .XrLabelCertStatus1.Visible = False
                        .XrLabelCertStatus2.Visible = False
                        .XrLabelCertStatus3.Visible = False
                    End If

                    If IsDBNull(myreader("DeputyName")) = True Then
                        .XrLabelDeputy1.Text = myreader("Weighmaster")
                        .XrLabelDeputy2.Text = myreader("Weighmaster")
                        .XrLabelDeputy3.Text = myreader("Weighmaster")
                    Else
                        .XrLabelDeputy1.Text = myreader("DeputyName")
                        .XrLabelDeputy2.Text = myreader("DeputyName")
                        .XrLabelDeputy3.Text = myreader("DeputyName")
                    End If

                    If NoNull(myreader("ReplacedCert")) = "" Then                 'Replaced this line: If IsDBNull(myreader("ReplacedCert")) = True Then
                        .XrLabelReplacesLabel1.Visible = False
                        .XrLabelReplacesLabel2.Visible = False
                        .XrLabelReplacesLabel3.Visible = False

                        .XrLabel174.Visible = False                             ' Replaces cert 1
                        .XrLabel113.Visible = False                             ' Replaces cert 2
                        .XrLabel178.Visible = False                             ' Replaces cert 3

                        .XrLabel174.BorderWidth = 0                             ' Replaces cert 1
                        .XrLabel113.BorderWidth = 0                             ' Replaces cert 2
                        .XrLabel178.BorderWidth = 0                             ' Replaces cert 3
                    Else
                        .XrLabel174.Text = myreader("ReplacedCert")               ' Replaces cert 1
                        .XrLabel113.Text = myreader("ReplacedCert")               ' Replaces cert 2
                        .XrLabel178.Text = myreader("ReplacedCert")               ' Replaces cert 3
                    End If
                End With
                rpt.Print()
            End If
        End While
        cn.Close()

请注意 ****** 该代码在某些 PC 上运行得非常好,这就是我最初没有提供代码的原因。我现在在联想 ThinkPad 上,代码使用数据读取器或适配器方法运行良好。它有时会在英特尔的 Nuc 10 i7 上运行良好,有时却不能像我上面描述的那样。*********

以下是使用 dataAdapter 和 datatable 方法的代码:

 Public Sub PrintSwatLoad(SwatKey As String)
    didPrint = True
    Try
        Dim sBarcode As String = ""
        Dim cn As New OleDbConnection(MDBConnect)
        Dim sSql As String = "" &
          "SELECT WeightCert, [SwatLog].[SwatDate], TareDate, SaleCode, " &
                "Species, Qual, SaleDesc, Trucker, TruckNo, TruckState, " &
                "TruckLic, TrlState, TrlLic, TruckType, Comments, TareLoad, " &
                "ScaleLoad, LoadNo, Logger, LogMethod, Block, Val(Gross) as GrossWt, " &
                "Val(Tare) as TareWt, Weight, PrintAvg, Brand, Commodity, SortCode, " &
                "Deck, UserInfo1, UserInfo2, EmergencyLevel, ReprintCount, " &
                "Reason, LocationName, Addr1, Addr2, OwnerName, LoggerName," &
                "Contract, Weighmaster, TT, Reprint, TareoutBarcode, PrintTare, TruckName, " &
                "ManualWeight, DeputyName, CertStatus, ReplacedCert  " &
          "FROM Swatlog INNER JOIN tblTempCert " &
            "ON [SwatLog].[SwatDate] = [tblTempCert].[SwatDate] " &
         "WHERE [tblTempCert].[SwatDate] = #" & SwatKey & "#"

        Dim cmd As New OleDbCommand(sSql, cn)
        Dim da As New OleDbDataAdapter(cmd)
        Dim ds As New DataSet
        Dim dt As New DataTable

        cn.Open()

        ''''''''''This is where it hangs using the dataAdapter fill'''''''''''
        da.Fill(dt)
        ''''''''''Above is where it hangs''''''''''''''''''''''''''''

        ds.Tables.Add(dt) ' added this to dataset
        dt.TableName = "dataset"
        cn.Close()


        If dt.Rows.Count > 0 Then     'ds.Tables(0).Rows.Count
            Dim WrkRow As DataRow = dt.Rows(0)    'ds.Tables(0).Rows(0)
            If IsTareout = True Then
                sBarcode = Trim(WrkRow("Trucker")) & WrkRow("TruckNo")
            End If

            Dim rSwatLaserCert As New XRSwatLaserCert
            rSwatLaserCert.DataSource = dt

            Dim rpt As New DevExpress.XtraReports.UI.ReportPrintTool(rSwatLaserCert)
            With rSwatLaserCert
                .XrBCTareOut.Text = sBarcode
                If Not (WrkRow("ManualWeight") = 1 Or WrkRow("ManualWeight") = 3) Then
                    .XrLabelManualGross1.Visible = False
                    .XrLabelManualGross2.Visible = False
                    .XrLabelManualGross3.Visible = False
                End If

                If Not (WrkRow("ManualWeight") = 2 Or WrkRow("ManualWeight") = 3) Then
                    .XrLabelManualTare1.Visible = False
                    .XrLabelManualTare2.Visible = False
                    .XrLabelManualTare3.Visible = False
                End If

                If WrkRow("CertStatus") = 1 Then
                ElseIf WrkRow("CertStatus") = 2 Then
                    .XrLabelCertStatus1.Text = "VOID"
                    .XrLabelCertStatus2.Text = "VOID"
                    .XrLabelCertStatus3.Text = "VOID"
                Else
                    .XrLabelCertStatus1.Visible = False
                    .XrLabelCertStatus2.Visible = False
                    .XrLabelCertStatus3.Visible = False
                End If

                If IsDBNull(WrkRow("DeputyName")) = True Then
                    .XrLabelDeputy1.Text = WrkRow("Weighmaster")
                    .XrLabelDeputy2.Text = WrkRow("Weighmaster")
                    .XrLabelDeputy3.Text = WrkRow("Weighmaster")
                Else
                    .XrLabelDeputy1.Text = WrkRow("DeputyName")
                    .XrLabelDeputy2.Text = WrkRow("DeputyName")
                    .XrLabelDeputy3.Text = WrkRow("DeputyName")
                End If

                If NoNull(WrkRow("ReplacedCert")) = "" Then                 'Replaced this line: If IsDBNull(WrkRow("ReplacedCert")) = True Then
                    .XrLabelReplacesLabel1.Visible = False
                    .XrLabelReplacesLabel2.Visible = False
                    .XrLabelReplacesLabel3.Visible = False

                    .XrLabel174.Visible = False                             ' Replaces cert 1
                    .XrLabel113.Visible = False                             ' Replaces cert 2
                    .XrLabel178.Visible = False                             ' Replaces cert 3

                    .XrLabel174.BorderWidth = 0                             ' Replaces cert 1
                    .XrLabel113.BorderWidth = 0                             ' Replaces cert 2
                    .XrLabel178.BorderWidth = 0                             ' Replaces cert 3
                Else
                    .XrLabel174.Text = WrkRow("ReplacedCert")               ' Replaces cert 1
                    .XrLabel113.Text = WrkRow("ReplacedCert")               ' Replaces cert 2
                    .XrLabel178.Text = WrkRow("ReplacedCert")               ' Replaces cert 3
                End If
            End With
            rpt.Print()
        End If
        ds.Tables.Remove("dataset")
        da.Dispose()
        Catch ex As Exception
        RecordEvent("Cert error:   " & SwatKey & " - " & Reason & " (" & ex.Message & ")", True)

    End Try
    didPrint = False
End Sub
   Public Sub GetKeyAndReason(ByRef sKey As String, ByRef sReason As String)
    Dim sSql As String = "SELECT SwatDate, Reason FROM tblTempCert"
    Dim cn As New OleDbConnection(MDBConnect)
    Dim da As New OleDbDataAdapter(sSql, cn)
    Dim ds As New DataSet

    Dim dt As New DataTable
    da.Fill(dt)
    If dt.Rows.Count > 0 Then
        Dim WorkRow1 As DataRow = dt.Rows(0)
        sKey = WorkRow1("SwatDate").ToString
        sReason = WorkRow1("Reason").ToString
    End If
    dt.Dispose()
    da.Dispose()
    cn.Dispose()
End Sub

您的 Access 数据库可能已损坏。下面的代码包含多种可能有用的方法,包括CompactAccessDatabase and CompactAccessDatabaseMDBOnly- 如果需要的话,压缩还可以修复数据库。由于没有为OP中提到的表提供数据类型,因此可能需要更新“CreateTblSwatLog”和“CreateTblTempCert”中的数据类型。

添加对您的项目的引用:

VS 2019:

  • Click Project
  • Select 添加参考
  • Click COM
  • Check Microsoft Jet 和复制对象 2.6 库
  • Check 微软 ADO 扩展。 6.0 DDL 和安全性
  • Check Microsoft DAO 3.6 对象库
  • Check Microsoft Access xx.x 对象库
  • Click 组件
  • Check 系统数据(如果尚未检查)

创建一个模块(名称:帮手)

Imports System.IO
Imports System.Data.OleDb

Module HelperAccess

    Private didPrint As Boolean = False
    'Private MDBConnect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\SWAT\Pclogs.mdb;User Id=admin;Password=;"
    Private MDBConnect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\SWAT\Pclogs.mdb;Mode=Share Exclusive;User Id=admin;Password=;"
    'Private MDBConnect As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\SWAT\Pclogs.mdb;Persist Security Info=False;"

    Public Property IsTareOut As Boolean = True

    Public Sub CompactAccessDatabase(filename As String)
        'Add reference
        'Project => Add Reference => COM => Microsoft Access xx.x Object Library

        'compacts Access database by copying the database to a new file and replacing the original file
        'Note: this method works with both .mdb and .accdb files

        Try
            If String.IsNullOrEmpty(filename) OrElse Not System.IO.File.Exists(filename) Then
                Throw New Exception("Error: Access database '" & filename & "' doesn't exist.")
            End If

            Dim fileExt As String = Path.GetExtension(filename).ToLower()

            Dim tempFilename As String = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) & "_temp" & Path.GetExtension(filename))

            Debug.WriteLine("Info: Compacting '" & filename & "'...")

            Dim dbe As New Microsoft.Office.Interop.Access.Dao.DBEngine

            'invoke CompactDatabase - compacts database to temp file
            dbe.CompactDatabase(filename, tempFilename)

            'delete original database file
            System.IO.File.Delete(filename)

            System.IO.File.Move(tempFilename, filename)

            'release COM object
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(dbe)

            Debug.WriteLine("Info: Database compacted: '" & filename & "'")
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub CompactAccessDatabaseMDBOnly(filename As String)
        'Add reference
        'Project => Add Reference => COM => Microsoft DAO 3.6 Object Library

        'compacts Access database by copying the database to a new file and replacing the original file
        'Note: this method works with only .mdb files

        Try
            If String.IsNullOrEmpty(filename) OrElse Not System.IO.File.Exists(filename) Then
                Throw New Exception("Error: Access database '" & filename & "' doesn't exist.")
            End If

            Dim fileExt As String = Path.GetExtension(filename).ToLower()

            Dim tempFilename As String = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) & "_temp" & Path.GetExtension(filename))

            Debug.WriteLine("Info: Compacting '" & filename & "'...")

            Dim dbe As New DAO.DBEngine

            'invoke CompactDatabase - compacts database to temp file
            dbe.CompactDatabase(filename, tempFilename)

            'delete original database file
            System.IO.File.Delete(filename)

            System.IO.File.Move(tempFilename, filename)

            'release COM object
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(dbe)

            Debug.WriteLine("Info: Database compacted: '" & filename & "'")
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub CompactAccessDatabaseMDBOnly2(filename As String)
        'Add reference
        'Project => Add Reference => COM => Microsoft Jet and Replication Objects 2.6 Library

        'compacts Access database by copying the database to a new file and replacing the original file
        'Note: this method is only for .mdb files

        Try
            If String.IsNullOrEmpty(filename) OrElse Not System.IO.File.Exists(filename) Then
                Throw New Exception("Error: Access database '" & filename & "' doesn't exist.")
            End If

            Dim fileExt As String = Path.GetExtension(filename).ToLower()

            'must be .mdb to compact
            If fileExt <> ".mdb" Then
                Throw New Exception("Error: Compacting database with '" & fileExt & "' isn't supported.")
            End If

            Dim connectionString As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Mode=Share Exclusive;User Id=admin;Password=;", filename)
            Dim tempFilename As String = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) & "_temp" & Path.GetExtension(filename))
            'Dim connectionStringTemp As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};", tempFilename)
            Dim connectionStringTemp As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5", tempFilename)

            'Debug.WriteLine("connectionString: " & connectionString)
            'Debug.WriteLine("tempFilename: " & tempFilename)
            'Debug.WriteLine("connectionStringTemp: " & connectionStringTemp)

            'create instance of Jet Replication Object
            Dim objJRO = Activator.CreateInstance(Type.GetTypeFromProgID("JRO.JetEngine"))

            'Engine Type: 
            '1: JET10
            '2: JET11
            '3: JET2x
            '4: JET3x
            '5: JET4x
            'Dim oParams = {connectionString, String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5", tempFilename)}
            Dim oParams = {connectionString, connectionStringTemp}

            Debug.WriteLine("Info: Compacting '" & filename & "'...")

            'invoke CompactDatabase - compacts database to temp file
            objJRO.GetType().InvokeMember("CompactDatabase", System.Reflection.BindingFlags.InvokeMethod, Nothing, objJRO, oParams)

            'delete original database file
            System.IO.File.Delete(filename)

            System.IO.File.Move(tempFilename, filename)

            'release COM object
            'System.Runtime.InteropServices.Marshal.ReleaseComObject(objJRO)
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objJRO)

            Debug.WriteLine("Info: Database compacted: '" & filename & "'")
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Function CreateDatabase() As String
        'Add reference
        'Project => Add Reference => COM => Microsoft ADO Ext. 6.0 for DDL and Security

        Dim result As String = String.Empty

        Dim cat As ADOX.Catalog = Nothing

        Try
            'create New instance
            cat = New ADOX.Catalog()

            'create Access database
            cat.Create(MDBConnect)

            'set value
            result = String.Format("Status: Database created.")

            Return result
        Catch ex As Exception
            'set value
            result = String.Format("Error (CreateDatabase): {0}(Connection String: {1})", ex.Message, MDBConnect)
            Return result
        Finally
            If cat IsNot Nothing Then
                'close connection
                cat.ActiveConnection.Close()

                'release COM object
                System.Runtime.InteropServices.Marshal.ReleaseComObject(cat)

                cat = Nothing
            End If
        End Try
    End Function

    Public Function CreateTblSwatLog() As String
        Dim result As String = String.Empty

        Dim tableName As String = "SwatLog"

        Dim sqlText = String.Empty
        sqlText = "CREATE TABLE SwatLog "
        sqlText += "(ID AUTOINCREMENT not null primary key,"
        sqlText += " [WeightCert] varchar(50),"
        sqlText += " [SwatDate] DateTime,"
        sqlText += " [TareDate] DateTime,"
        sqlText += " [SaleCode] varchar(50),"
        sqlText += " [Species] varchar(50),"
        sqlText += " [Qual] varchar(50),"
        sqlText += " [SaleDesc] varchar(50),"
        sqlText += " [Trucker] varchar(50),"
        sqlText += " [TruckNo] varchar(50),"
        sqlText += " [TruckState] varchar(50),"
        sqlText += " [TruckLic] varchar(50),"
        sqlText += " [TrlState] varchar(50),"
        sqlText += " [TrlLic] varchar(50),"
        sqlText += " [TruckType] varchar(50),"
        sqlText += " [Comments] varchar(150),"
        sqlText += " [TareLoad] varchar(50),"
        sqlText += " [ScaleLoad] varchar(50),"
        sqlText += " [LoadNo] integer,"
        sqlText += " [Logger] varchar(50),"
        sqlText += " [LogMethod] varchar(50),"
        sqlText += " [Block] varchar(50),"
        sqlText += " [Gross] varchar(25),"
        sqlText += " [Tare] varchar(25),"
        sqlText += " [Weight] numeric(18,2),"
        sqlText += " [PrintAvg] numeric(18,2),"
        sqlText += " [Brand] varchar(50),"
        sqlText += " [Commodity] varchar(50),"
        sqlText += " [SortCode] varchar(50),"
        sqlText += " [Deck] varchar(50),"
        sqlText += " [UserInfo1] varchar(50),"
        sqlText += " [UserInfo2] varchar(50),"
        sqlText += " [EmergencyLevel] integer,"
        sqlText += " [ReprintCount] integer,"
        sqlText += " [Reason] varchar(75),"
        sqlText += " [LocationName] varchar(50),"
        sqlText += " [Addr1] varchar(50),"
        sqlText += " [Addr2] varchar(50),"
        sqlText += " [OwnerName] varchar(50),"
        sqlText += " [LoggerName] varchar(75),"
        sqlText += " [Contract] varchar(50),"
        sqlText += " [Weighmaster] varchar(50),"
        sqlText += " [TT] varchar(50),"
        sqlText += " [Reprint] bit,"
        sqlText += " [TareoutBarcode] Longbinary,"
        sqlText += " [PrintTare] bit,"
        sqlText += " [TruckName] varchar(50),"
        sqlText += " [ManualWeight] varchar(50),"
        sqlText += " [DeputyName] varchar(50),"
        sqlText += " [CertStatus] varchar(50),"
        sqlText += " [ReplacedCert] varchar(50));"

        Try
            Debug.WriteLine(sqlText)

            'create database table
            ExecuteNonQuery(sqlText)

            result = String.Format("Table created: '{0}'", tableName)

        Catch ex As OleDbException
            'result = String.Format("Error (CreateTblSwatLog - OleDbException): Table creation failed: '{0}'; {1}", tableName, ex.Message)
            Throw ex
        Catch ex As Exception
            'result = String.Format("Error (CreateTblSwatLog): Table creation failed: '{0}'; {1}", tableName, ex.Message)
            Throw ex
        End Try

        Return result
    End Function

    Public Function CreateTblSwatLog2() As String
        Dim result As String = String.Empty

        Dim tableName As String = "SwatLog"

        Dim sqlText = String.Empty
        sqlText = "CREATE TABLE SwatLog "
        sqlText += "(ID AUTOINCREMENT not null primary key,"
        sqlText += " [WeightCert] varchar(50),"
        sqlText += " [SwatDate] DateTime,"
        sqlText += " [TareDate] DateTime,"
        sqlText += " [SaleCode] varchar(50),"
        sqlText += " [Species] varchar(50),"
        sqlText += " [Qual] varchar(50),"
        sqlText += " [SaleDesc] varchar(50),"
        sqlText += " [Trucker] varchar(50),"
        sqlText += " [TruckNo] varchar(50),"
        sqlText += " [TruckState] varchar(50),"
        sqlText += " [TruckLic] varchar(50),"
        sqlText += " [TrlState] varchar(50),"
        sqlText += " [TrlLic] varchar(50),"
        sqlText += " [TruckType] varchar(50),"
        sqlText += " [Comments] varchar(150),"
        sqlText += " [TareLoad] varchar(50),"
        sqlText += " [ScaleLoad] varchar(50),"
        sqlText += " [LoadNo] integer,"
        sqlText += " [Logger] varchar(50),"
        sqlText += " [LogMethod] varchar(50),"
        sqlText += " [Block] varchar(50),"
        sqlText += " [Gross] numeric(18,2),"
        sqlText += " [Tare] numeric(18,2),"
        sqlText += " [Weight] numeric(18,2),"
        sqlText += " [PrintAvg] numeric(18,2),"
        sqlText += " [Brand] varchar(50),"
        sqlText += " [Commodity] varchar(50),"
        sqlText += " [SortCode] varchar(50),"
        sqlText += " [Deck] varchar(50),"
        sqlText += " [UserInfo1] varchar(50),"
        sqlText += " [UserInfo2] varchar(50),"
        sqlText += " [EmergencyLevel] integer,"
        sqlText += " [ReprintCount] integer,"
        sqlText += " [Reason] varchar(75),"
        sqlText += " [LocationName] varchar(50),"
        sqlText += " [Addr1] varchar(50),"
        sqlText += " [Addr2] varchar(50),"
        sqlText += " [OwnerName] varchar(50),"
        sqlText += " [LoggerName] varchar(75),"
        sqlText += " [Contract] varchar(50),"
        sqlText += " [Weighmaster] varchar(50),"
        sqlText += " [TT] varchar(50),"
        sqlText += " [Reprint] bit,"
        sqlText += " [TareoutBarcode] Longbinary,"
        sqlText += " [PrintTare] bit,"
        sqlText += " [TruckName] varchar(50),"
        sqlText += " [ManualWeight] varchar(50),"
        sqlText += " [DeputyName] varchar(50),"
        sqlText += " [CertStatus] varchar(50),"
        sqlText += " [ReplacedCert] varchar(50));"

        Try
            Debug.WriteLine(sqlText)

            'create database table
            ExecuteNonQuery(sqlText)

            result = String.Format("Table created: '{0}'", tableName)

        Catch ex As OleDbException
            'result = String.Format("Error (CreateTblSwatLog - OleDbException): Table creation failed: '{0}'; {1}", tableName, ex.Message)
            Throw ex
        Catch ex As Exception
            'result = String.Format("Error (CreateTblSwatLog): Table creation failed: '{0}'; {1}", tableName, ex.Message)
            Throw ex
        End Try

        Return result
    End Function

    Public Function CreateTblTempCert() As String
        Dim result As String = String.Empty

        Dim tableName As String = "tblTempCert"

        Dim sqlText = String.Empty
        sqlText = "CREATE TABLE tblTempCert "
        sqlText += "(ID AUTOINCREMENT not null primary key,"
        sqlText += " [SwatDate] DateTime);"

        Try
            'create database table
            ExecuteNonQuery(sqlText)

            result = String.Format("Table created: '{0}'", tableName)

        Catch ex As OleDbException
            'result = String.Format("Error (CreateTblSwatLog - OleDbException): Table creation failed: '{0}'; {1}", tableName, ex.Message)
            Throw ex
        Catch ex As Exception
            'result = String.Format("Error (CreateTblSwatLog): Table creation failed: '{0}'; {1}", tableName, ex.Message)
            Throw ex
        End Try

        Return result
    End Function

    Private Function ExecuteNonQuery(sqlText As String) As Integer
        Dim rowsAffected As Integer = 0

        'used for insert/update

        'create new connection
        Using cn As OleDbConnection = New OleDbConnection(MDBConnect)
            'open
            cn.Open()

            'create new instance
            Using cmd As OleDbCommand = New OleDbCommand(sqlText, cn)
                'execute
                rowsAffected = cmd.ExecuteNonQuery()
            End Using
        End Using

        Return rowsAffected
    End Function



    Public Sub PrintSwatLoad(SwatKey As String)
        'set value
        didPrint = True

        'create new instance
        Dim dt As New DataTable

        'create new instance
        Dim ds As New DataSet

        Try
            Dim sBarcode As String = ""

            Dim sSql As String = String.Empty

            'sSql = "SELECT WeightCert, [SwatLog].[SwatDate], TareDate, SaleCode, " &
            '        "Species, Qual, SaleDesc, Trucker, TruckNo, TruckState, " &
            '        "TruckLic, TrlState, TrlLic, TruckType, Comments, TareLoad, " &
            '        "ScaleLoad, LoadNo, Logger, LogMethod, Block, Val(Gross) as GrossWt, " &
            '        "Val(Tare) as TareWt, Weight, PrintAvg, Brand, Commodity, SortCode, " &
            '        "Deck, UserInfo1, UserInfo2, EmergencyLevel, ReprintCount, " &
            '        "Reason, LocationName, Addr1, Addr2, OwnerName, LoggerName," &
            '        "Contract, Weighmaster, TT, Reprint, TareoutBarcode, PrintTare, TruckName, " &
            '        "ManualWeight, DeputyName, CertStatus, ReplacedCert  " &
            '        "FROM Swatlog INNER JOIN tblTempCert " &
            '        "ON [SwatLog].[SwatDate] = [tblTempCert].[SwatDate] " &
            '        "WHERE [tblTempCert].[SwatDate] = ?;"

            sSql = "SELECT WeightCert, [SwatLog].[SwatDate], TareDate, SaleCode, " &
                    "Species, Qual, SaleDesc, Trucker, TruckNo, TruckState, " &
                    "TruckLic, TrlState, TrlLic, TruckType, Comments, TareLoad, " &
                    "ScaleLoad, LoadNo, Logger, LogMethod, Block, Gross as GrossWt, " &
                    "Tare as TareWt, Weight, PrintAvg, Brand, Commodity, SortCode, " &
                    "Deck, UserInfo1, UserInfo2, EmergencyLevel, ReprintCount, " &
                    "Reason, LocationName, Addr1, Addr2, OwnerName, LoggerName," &
                    "Contract, Weighmaster, TT, Reprint, TareoutBarcode, PrintTare, TruckName, " &
                    "ManualWeight, DeputyName, CertStatus, ReplacedCert  " &
                    "FROM Swatlog INNER JOIN tblTempCert " &
                    "ON [SwatLog].[SwatDate] = [tblTempCert].[SwatDate] " &
                    "WHERE [tblTempCert].[SwatDate] = ?;"

            Using cn As New OleDbConnection(MDBConnect)
                'open
                cn.Open()

                Dim swatDate As DateTime = DateTime.MaxValue

                'try to convert to DateTime
                DateTime.TryParse(SwatKey, swatDate)

                Using cmd As New OleDbCommand(sSql, cn)
                    'add parameters
                    cmd.Parameters.Add("!swatDate", OleDbType.DBDate).Value = swatDate

                    'ToDo: remove the following code that is for debugging
                    For Each p As OleDbParameter In cmd.Parameters
                        Debug.WriteLine(p.ParameterName & ": " & p.Value.ToString())
                    Next

                    Debug.WriteLine(cmd.CommandText)

                    Using da As New OleDbDataAdapter(cmd)

                        'fill DataTable
                        da.Fill(dt)

                        'add to DataSet
                        ds.Tables.Add(dt) ' added this to dataset
                        dt.TableName = "dataset"

                        'Debug.WriteLine("table count: " & ds.Tables.Count)

                        'For i As Integer = 0 To ds.Tables.Count - 1 Step 1
                        'Debug.WriteLine("table: " & ds.Tables(i).TableName)
                        'Next
                    End Using
                End Using
            End Using

            If dt.Rows.Count > 0 Then     'ds.Tables(0).Rows.Count
                Dim WrkRow As DataRow = dt.Rows(0)    'ds.Tables(0).Rows(0)
                If IsTareOut = True Then
                    'sBarcode = Trim(WrkRow("Trucker")) & WrkRow("TruckNo")
                    sBarcode = Trim(WrkRow("Trucker")) & " - " & WrkRow("TruckNo")

                    Debug.WriteLine("sBarcode: " & sBarcode)
                End If

                'ToDo: add desired code

            End If
        Catch ex As OleDbException
            'ToDo: add desired code
            'RecordEvent("Cert error:   " & SwatKey & " - " & Reason & " (" & ex.Message & ")", True)
            Throw ex
        Catch ex As Exception
            'ToDo: add desired code
            'RecordEvent("Cert error:   " & SwatKey & " - " & Reason & " (" & ex.Message & ")", True)
            Throw ex
        End Try

        'set value
        didPrint = False
    End Sub

    Public Function TblSwatLogInsert(swatDate As DateTime, trucker As String, truckNo As String, weight As String, tare As String, comments As String) As Integer
        Dim rowsAffected As Integer = 0

        Dim sqlText As String = String.Empty
        sqlText = "INSERT INTO SwatLog ([SwatDate], [Trucker], [TruckNo], [Weight], [Tare], [Comments]) VALUES (?, ?, ?, ?, ?, ?);"

        Try
            'insert data to database
            'create new connection
            Using cn As OleDbConnection = New OleDbConnection(MDBConnect)
                'open
                cn.Open()

                'create new instance
                Using cmd As OleDbCommand = New OleDbCommand(sqlText, cn)

                    'OLEDB doesn't use named parameters in SQL. Any names specified will be discarded and replaced with '?'
                    'However, specifying names in the parameter 'Add' statement can be useful for debugging
                    'Since OLEDB uses anonymous names, the order which the parameters are added is important
                    'if a column is referenced more than once in the SQL, then it must be added as a parameter more than once
                    'parameters must be added in the order that they are specified in the SQL
                    'if a value is null, the value must be assigned as: DBNull.Value

                    'add parameters
                    With cmd.Parameters
                        .Add("!swatDate", OleDbType.DBDate).Value = swatDate
                        .Add("!trucker", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(trucker), DBNull.Value, trucker)
                        .Add("!truckNo", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(truckNo), DBNull.Value, truckNo)
                        .Add("!weight", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(weight), 0, weight)
                        .Add("!tare", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(tare), 0, tare)
                        .Add("!comments", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(comments), DBNull.Value, comments)
                    End With

                    'ToDo: remove the following code that is for debugging
                    'For Each p As OleDbParameter In cmd.Parameters
                    'Debug.WriteLine(p.ParameterName & ": " & p.Value.ToString())
                    'Next

                    'execute
                    rowsAffected = cmd.ExecuteNonQuery()
                End Using
            End Using
        Catch ex As OleDbException
            Debug.WriteLine("Error (TblSwatLogInsert - OleDbException) - " & ex.Message & "(" & sqlText & ")")
            Throw ex
        Catch ex As Exception
            Debug.WriteLine("Error (TblSwatLogInsert) - " & ex.Message & "(" & sqlText & ")")
            Throw ex

        End Try

        Return rowsAffected
    End Function

    Public Function TblTempCertInsert(swatDate As DateTime) As Integer
        Dim rowsAffected As Integer = 0

        Dim sqlText As String = String.Empty
        sqlText = "INSERT INTO tblTempCert ([SwatDate]) VALUES (?);"

        Try
            'insert data to database
            'create new connection
            Using cn As OleDbConnection = New OleDbConnection(MDBConnect)
                'open
                cn.Open()

                'create new instance
                Using cmd As OleDbCommand = New OleDbCommand(sqlText, cn)

                    'OLEDB doesn't use named parameters in SQL. Any names specified will be discarded and replaced with '?'
                    'However, specifying names in the parameter 'Add' statement can be useful for debugging
                    'Since OLEDB uses anonymous names, the order which the parameters are added is important
                    'if a column is referenced more than once in the SQL, then it must be added as a parameter more than once
                    'parameters must be added in the order that they are specified in the SQL
                    'if a value is null, the value must be assigned as: DBNull.Value

                    'add parameters
                    With cmd.Parameters
                        .Add("!swatDate", OleDbType.DBDate).Value = swatDate
                    End With

                    'ToDo: remove the following code that is for debugging
                    'For Each p As OleDbParameter In cmd.Parameters
                    'Debug.WriteLine(p.ParameterName & ": " & p.Value.ToString())
                    'Next

                    'execute
                    rowsAffected = cmd.ExecuteNonQuery()
                End Using
            End Using
        Catch ex As OleDbException
            Debug.WriteLine("Error (TblTempCertInsert - OleDbException) - " & ex.Message & "(" & sqlText & ")")
            Throw ex
        Catch ex As Exception
            Debug.WriteLine("Error (TblTempCertInsert) - " & ex.Message & "(" & sqlText & ")")
            Throw ex

        End Try

        Return rowsAffected
    End Function
End Module

资源

  • 转换 Access OLE 对象图像以在 Datagridview vb.net 中显示 https://stackoverflow.com/questions/69624053/converting-access-ole-object-image-to-show-in-datagridview-vb-net/69638011#69638011
  • 使用 C# 压缩和修复 Access 数据库? https://social.msdn.microsoft.com/Forums/en-US/1062b0c3-30de-4590-aa56-b2b87b7b4452/compact-and-repair-access-database-using-c-?forum=accessdev
  • 如何通过 .NET 代码压缩和修复 ACCESS 2007 数据库? https://stackoverflow.com/questions/1548245/how-do-i-compact-and-repair-an-access-2007-database-by-net-code
  • jro.jetengine 未被识别.. https://www.vbforums.com/showthread.php?326407-jro-jetengine-not-being-recognised
  • 使用 C# 和后期绑定压缩和修复 Access 数据库 https://www.codeproject.com/Articles/7775/Compact-and-Repair-Access-Database-using-Csharp-an
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

OleDbDataAdapter Fill 和 OleDbDataReader 需要 3-5 分钟来填充 的相关文章

随机推荐

  • Postman请求带body表单数据转json

    我和邮递员有问题 For one side I can make this request with the body in form data 但是 当我尝试使用 raw json 中的正文发送相同的请求时 我得到了 我正在尝试通过 An
  • 为什么 javascript 不在加载 Ext.Ajax.Request 的 .php 文件中执行?

    我想通过 ajax 加载 php 文件 该文件在加载时执行 ExtJS 脚本 从而修改 DOM 中已存在的现有 ExtJS 对象 但是 我什至无法从正在加载的页面执行 JavascriptExt Ajax request Firebug N
  • 如何通过代码编程获取设备的 IMEI/ESN 号码但在 android > 6 中

    我的安卓版本是棉花糖6 0 如何以编程方式在 android gt 6 中查找 获取 imei 号码 注意 我在 AndroidManifest xml 文件中添加了 READ PHONE STATE 权限
  • Laravel - 会话返回 null

    我第一次在 Laravel 中使用会话 并且尝试执行多步骤形式 所以我认为使用会话将是一个明智之举 但是下面的代码返回一个空值 我做错了什么 user information name gt request gt name email gt
  • 扩展 CodeIgniter 中的控制器类

    I have class MY Controller extends CI Controller和大配置文件部分的通用逻辑 所以我尝试创建class Profile extends MY Controller正如我所理解的那样 配置文件部分
  • 如何使用自定义元素将子自定义元素包装到 div 中

    我正在尝试创建一个包装器自定义元素 将其子自定义元素包装到 div 中 但子元素没有被包装 相反 一个空的 div 被插入到子元素之前的包装元素中
  • 如何对私有变量进行单元测试?

    考虑一个链表类 我维护 2 个私有变量 1 firstNode 和 2 lastNode 因此 这些变量仅供内部使用 不通过 getter 公开 我想测试操作是否按预期修改这两个变量 例如 如果最后一个节点是重复的 则消除排序链表中的重复应
  • Blade 文件中的 if else 条件(laravel 5.3)

    我想检查一下if else我的刀片文件中的状况 我想检查一下情况 user gt status waiting 如下面给出的代码 输出按我的预期正确返回 但随着我的输出 我发现打印了大括号 我想删除结果中的大括号 我的有什么问题吗if健康
  • 计时器每 5 分钟运行一次

    如何每 5 分钟运行一些函数 示例 我想跑步sendRequest 仅在 14 00 14 05 14 10 等时间 我想用 C 以编程方式完成它 该应用程序是 Windows 服务 Use System Threading Timer h
  • Mockito:模拟对象,不是成员,但内联创建

    我有一个类执行以下操作 public class Transformer public void transform final Car car throws IOException switch car getType case OFFR
  • 如何以 vmware 清晰度动态切换主题

    Vmware Clarity 0 10 16 刚刚发布了新的深色主题 这很棒 他们描述了如何添加新主题 但没有描述在页面内动态更改它的可能性 是因为不可行吗 如果是的话 我该如何使用 Angular 4 来做到这一点 有什么网站可以帮助我解
  • 在 Debezium Mysql Connector 中将更多表列入白名单的有效方法

    将新表列入 debezium mysql 连接器白名单是否遵循任何最佳实践 我们在 CDC 流程中使用 debezium mysql 连接器 并且出现了一个用例 将更多表列入连接器配置的白名单 以下是正在使用的 Debezium 的版本详细
  • RoR,无法从 DateTime/TimeWithZone 迭代

    我有一个简单的任务 我想获取开始日期和结束日期并循环天 日期 这段代码正在我的 db seed rake 任务中使用 目前 我的代码已经经历了以下尝试 someModel start date to datetime someModel e
  • 使用confirm()作为if的条件?

    我有这个功能 function RemoveProduct if confirm Poista return true return true else return false 当您单击页面上的 删除 按钮时 它应该询问是否应该删除产品
  • HTML SRC 属性 - 使用 html 代码而不是 URL

    有没有办法使用纯 html 代码在框架内显示 而不必链接到特定的 URL 文件 例如 不是这样的 但就像这样 也许您可以将 HTML 注入 iFrame Frame 中 如本文所述 将 HTML 注入 IFrame http softwar
  • 如果兄弟节点具有特定值,如何使用 XPath 选择节点?

    我有以下文件 a a
  • 执行控制台命令并获取其输出

    我想知道 在 Visual Basic 2008 中 如何执行外部控制台 命令行 命令并在没有中间文件的帮助下获取其输出 以加快速度 看一下ProcessStartInfo RedirectStandardOutput http msdn
  • Android KeyStore - 密钥并不总是持久存在

    在我的应用程序中 我们使用 RSA 密钥 该密钥是应用程序在第一次启动时生成的 使用 Android 密钥存储 由于未知原因 应用程序无法从某些设备上的密钥存储中检索密钥 我检查了日志 但找不到此错误与特定操作系统版本或特定设备型号之间的关
  • 有谁知道 pymongo 中 2dsphere 索引的工作示例吗?

    我正在尝试编写一个脚本来执行此处提到的基本 2dsphere 索引操作2dsphere http docs mongodb org manual core 2dsphere 使用 pymongo 我找不到任何例子来弄清楚 这是我迄今为止的尝
  • OleDbDataAdapter Fill 和 OleDbDataReader 需要 3-5 分钟来填充

    这是一个非常奇怪的问题 因为它只发生在随机的全新 Windows 10 电脑上 填充数据适配器或数据读取器需要 1 5 分钟 这是从 Windows 7 旧电脑升级到全新 Windows 10 电脑时发生的第三台电脑 第一次出现是在一年前