Sql插入查询不插入

时间:2013-12-26 19:57:44

标签: vb.net visual-studio-2010 visual-studio ms-access

我无法通过sql查询将数据插入到访问数据库中。如果我在访问中的sql视图中运行查询它插入正常,所以我想这会在我的代码中留下错误。我确信我已经犯了一个根本性的错误,如果有人能指出它,我将不胜感激。感谢

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

        Try

        DBConnection.connect()

            sql = "SELECT MAX([Request no]) from Requests WHERE Customer = '" & cmbCustomer.Text & "' "

            Dim cmd As New OleDb.OleDbCommand

            Dim id As String
            Dim requestor As String = "BT"
            Dim intake As String = "I"
            Dim status As String = "O"

        'cmd.Parameters.AddWithValue("@p1", cmbCustomer.Text)

            cmd.CommandText = sql
            cmd.Connection = oledbCnn
            dr = cmd.ExecuteReader

        While dr.Read()

                id = CStr(dr.Item(0))
                id = CStr(CDbl(id) + 1)


            End While

            sql = "INSERT INTO Requests ([Request no], Customer, Dept, Type, [Service level], [Date-time received], [Received by], [Date-time due], Quantity, [Cust requestor], Status ) " &
            "VALUES ('" & id & "', '" & cmbCustomer.Text.ToUpper & "', '" & cmbDept.Text & "', '" & intake.ToString & "', '" & rbServiceLevel.ToString & "', NOW(), '" & requestor.ToString & "', '" & dtpDateDue.Value & "', '" & txtBoxQuantity.Text & "', '" & requestor.ToString & "', '" & status & "')"

            cmd.Dispose()
            dr.Close()
            oledbCnn.Close()

        Catch ex As Exception

            MessageBox.Show(ex.Message)

        End Try

    End Sub

DBCONNECT

Imports System.Data.OleDb

Module DBConnection

    Public connetionString As String = My.Settings.storageConnectionString
    Public oledbCnn As New OleDbConnection
    Public oledbCmd As OleDbCommand
    Public dr As OleDbDataReader
    Public sql As String

    Sub connect()

        'connetionString = My.Settings.storageConnectionString
        oledbCnn.ConnectionString = connetionString
        oledbCnn.Open()

    End Sub

End Module

1 个答案:

答案 0 :(得分:2)

您的问题是您正在构建SQL查询,但实际上并未执行它。 试试这个:

        End While

        dr.Close()

        sql = "INSERT INTO Requests ([Request no], Customer, Dept, Type, [Service level], [Date-time received], [Received by], [Date-time due], Quantity, [Cust requestor], Status ) " & _
        "VALUES ('" & id & "', '" & cmbCustomer.Text.ToUpper & "', '" & cmbDept.Text & "', '" & intake.ToString & "', '" & rbServiceLevel.ToString & "', NOW(), '" & requestor.ToString & "', '" & dtpDateDue.Value & "', '" & txtBoxQuantity.Text & "', '" & requestor.ToString & "', '" & status & "')"

        cmd.CommandText = sql
        cmd.ExecuteNonQuery()

        cmd.Dispose()
        oledbCnn.Close()

    Catch ex As Exception

但请听@LarsTech - 在构建SQL命令时查找parametrized query而不是字符串连接,否则您需要对SQL注入负责(有人可以欺骗文本框中的数据并导致数据丢失)

附注:如果您要从数据库中检索单个值 - 而不是ExecuteReader,请查找ExecuteScalar