Проверьте и поймайте «Вставьте» ошибки для доступа к БД - PullRequest
0 голосов
/ 09 июня 2011

У меня есть программа отгрузки в VB.Net, которая записывает в БД Access при обработке груза.Во время обработки возникают две вставки: первая инструкция вставки записывает общую информацию о пакете.

    Private Function AddToShipmentDatabase()
    'Prevent null errors from database by changing empty fields to empty strings 
    If ShipmentInformation.CreditCardInfo = Nothing Then
        ShipmentInformation.CreditCardInfo = ""
    End If
    If ShipmentInformation.Tracking = Nothing Then
        ShipmentInformation.Tracking = ""
    End If
    If ShipmentInformation.TransactionId = Nothing Then
        ShipmentInformation.TransactionId = ""
    End If

    'Connect to local database and upload the information 
    'stored in the shipment information structure
    Dim strConnectionString As String = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" & My.Settings.DBFileLocation
    Dim objConnection As New OleDb.OleDbConnection(strConnectionString)
    Dim objCommand As New OleDbCommand
    objCommand.Connection = objConnection
    objCommand.CommandText = "INSERT INTO [MailLog] ([CustomerId], [ShipDate], [CustomerName], [Service], [Tracking], [Address], [RxCount], [Charge], [CreditCardInfo], [TransactionId]) VALUES(@CustomerId, @ShipDate, @CustomerName, @Service, @Tracking, @Address, @RxCount, @Charge, @CreditCardInfo, @TransactionId)"
    objCommand.Parameters.AddWithValue("@CustomerId", ShipmentInformation.CustomerId)
    objCommand.Parameters.AddWithValue("@ShipDate", ShipmentInformation.ShipDate)
    objCommand.Parameters.AddWithValue("@CustomerName", ShipmentInformation.CustomerName)
    objCommand.Parameters.AddWithValue("@Service", ShipmentInformation.Service)
    objCommand.Parameters.AddWithValue("@Tracking", ShipmentInformation.Tracking)
    objCommand.Parameters.AddWithValue("@Address", ShipmentInformation.Address)
    objCommand.Parameters.AddWithValue("@RxCount", ShipmentInformation.RxCount)
    objCommand.Parameters.AddWithValue("@Charge", ShipmentInformation.Charge)
    objCommand.Parameters.AddWithValue("@CreditCardInfo", ShipmentInformation.CreditCardInfo)
    objCommand.Parameters.AddWithValue("@TransactionId", ShipmentInformation.TransactionId)

    'Connect to database and add record
    Dim intRecord As Integer = Nothing
    objConnection.Open()
    objCommand.ExecuteNonQuery()
    Do Until intRecord <> Nothing
        objCommand.CommandText = "SELECT @@IDENTITY"
        intRecord = objCommand.ExecuteScalar()
        objConnection.Close()
    Loop
    Return intRecord
End Function

Вторая 'Вставка' - это подробный список из сетки данных содержимого пакета.Первый возвращает идентификатор записи, который используется во втором листинге для сопоставления деталей отгрузки с отгрузками

    Private Sub LogPackage(ByVal RecordId As Integer)

    'Loop through the records in the log and add to database
    For i As Integer = 0 To (dgLog.Rows.Count - 1)
        Dim strValues(4) As String
        'Id
        strValues(0) = RecordId
        'RxNumber
        strValues(1) = dgLog.Rows(i).Cells(3).Value.ToString
        'DrugName
        strValues(2) = dgLog.Rows(i).Cells(6).Value.ToString
        'Quantity
        strValues(3) = dgLog.Rows(i).Cells(4).Value.ToString
        'Charge
        strValues(4) = dgLog.Rows(i).Cells(5).Value.ToString

        'Connect to local database and upload the information 
        'stored in the log datagrid
        Dim strConnectionString As String = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" & My.Settings.DBFileLocation
        Dim objConnection As New OleDb.OleDbConnection(strConnectionString)
        Dim objCommand As New OleDbCommand
        objCommand.Connection = objConnection
        objCommand.CommandText = "INSERT INTO [ShipmentDetails] ([MailLogId], [RxNumber], [DrugName], [Quantity], [Charge]) VALUES(@MailLogId, @RxNumber, @DrugName, @Quantity, @Charge)"
        objCommand.Parameters.AddWithValue("@MailLogId", strValues(0))
        objCommand.Parameters.AddWithValue("@RxNumber", strValues(1))
        objCommand.Parameters.AddWithValue("@DrugName", strValues(2))
        objCommand.Parameters.AddWithValue("@Quantity", strValues(3))
        objCommand.Parameters.AddWithValue("@Charge", strValues(4))

        'Connect to database and add record
        objConnection.Open()
        objCommand.ExecuteNonQuery()
        objConnection.Close()
    Next
End Sub

Моя проблема заключается в том, что в некоторых случаях содержимое пакета не записывается.Точнее говоря, один элемент, когда вставка не удалась, отсутствует.Если отправлены два товара, регистрируется только один.Три отправлены, два зарегистрированы.И т.д ... Я был бы признателен за любую помощь, чтобы выяснить это.Спасибо!

1 Ответ

0 голосов
/ 10 июня 2011

Я только что закончил тем, что добавил цикл в оператор вставки и установил результат выполнения без запроса в целое число.Теперь оператор вставки зацикливается до тех пор, пока результат вставки не будет равен 1

dim intRecord as integer = Nothing
Do Until intRecord = 1
//CODE
//CODE
//CODE
intRecord = objCommand.ExecuteNonQuery()
Loop

.Спасибо!

...