我运行项目时遇到错误

时间:2015-01-03 17:21:08

标签: vb.net

当我运行我的项目时,它一直在给我错误。第一个例外是da.Fill(dt)。它说IErrorInfo.GetDescription失败了E_FAIL(0x80004005)。 第二个例外是cmd.ExecuteNonQuery(),并在INSERT INTO语句中说出语法错误。 请帮我。我对VB很陌生,所以即使我整天看着它也无法看到问题。

Public Class Telephone_Bill

Dim cnn As New OleDb.OleDbConnection
Private Sub RefreshData()
    If Not cnn.State = ConnectionState.Open Then
        cnn.Open()
    End If

    Dim da As New OleDb.OleDbDataAdapter("SELECT Month as [Month], " & _
                                         "Day as [Day], Year, Amount Paid, Amount Due, Mode of Payment, Company Name " & _
                                         " FROM Transactions ORDER BY Month", cnn)

    Dim dt As New DataTable

    Transaction_Log.dgvTransaction.DataSource = dt

    da.Fill(dt)



    cnn.Close()
End Sub

Private Sub btnProceed_Click(sender As System.Object, e As System.EventArgs) Handles btnProceed.Click


    Dim cmd As New OleDb.OleDbCommand
    If Not cnn.State = ConnectionState.Open Then
        cnn.Open()
    End If

    cmd.Connection = cnn
    cmd.CommandText = "INSERT INTO Transactions([Month], [Day], [Year], AmountPaid, AmountDue, ModeofPayment, CompanyName) " & _
                        " VALUES(" & cboMonth1.SelectedItem & ",'" & cboDay1.SelectedItem & "','" & _
                        cboYear1.SelectedItem & "','" & txtAmount.Text & "','" & _
                        txtTotalCharges.Text & "','" & cboMonetary.SelectedItem & "','" & _
                        txtCompName.Text & "')"
    cmd.ExecuteNonQuery()

    RefreshData()

    cnn.Close()
End Sub

Private Sub Telephone_Bill_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    cnn = New OleDb.OleDbConnection
    cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\Accounts for Bill Payment Center.accdb"

    Me.RefreshData()

End Sub

结束班

1 个答案:

答案 0 :(得分:2)

Fill中的第一个错误可能是由于使用了保留关键字,并且带有空格的字段名称周围缺少方括号(Month, Day, Year都是许多数据库系统的保留关键字,需要使用方括号来使用它们在查询文本中)

Dim da As New OleDb.OleDbDataAdapter("SELECT [Month], " & _
                                     "[Day], [Year], [Amount Paid], [Amount Due], " & _ 
                                     "[Mode of Payment], [Company Name] " & _
                                     " FROM Transactions ORDER BY [Month]", cnn)

但是,您的字段名称是否包含有效空格尚不清楚 在INSERT语句中,相同的字段似乎没有空格。因此,如果它们有空格,则需要将它们封装在方括号中,否则,您可以将它们保留在INSERT查询中。

应使用适当的参数化方法

修复INSERT INTO中的错误
cmd.CommandText = "INSERT INTO Transactions([Month], [Day], [Year], " & _ 
                  "AmountPaid, AmountDue, ModeofPayment, CompanyName) " & _
                   " VALUES(?,?,?,?,?,?,?)"
cmd.Parameters.AddWithValue("@p1", Convert.ToInt32(cboMonth1.SelectedItem))
cmd.Parameters.AddWithValue("@p2", cboDay1.SelectedItem.ToString)
... and so on for the other fields....

请注意,在使用参数和AddWithValue方法时,您应该非常精确地确定传递给参数的值的类型。如果基础字段需要数值,则应按预期将值转换为适当的数据类型。例如AmountPaid和AmountDue似乎是数字字段,您应该将用户输入转换为适当的数据类型(十进制?)