0

我的 ADD 按钮上有这个代码,还有其他方法可以缩短这个代码语句。

Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click

    On Error GoTo ErrSQL

    Dim cmd As New OleDb.OleDbCommand
    If Not cnn.State = ConnectionState.Open Then
        'Open connection if it is not yet open
        cnn.Open()
    End If
    cmd.Connection = cnn
    'check whether add new update
    If Me.txtstdID.Tag & "" = "" Then
        'add new
        'add data to table
        cmd.CommandText = "INSERT INTO inventory (ID,BRAND,SPECIFICATION,STATUS) Values ('" & Me.txtstdID.Text & "','" & Me.cboBrand.Text & "','" & Me.txtDescription.Text & "','" & strStat & "')"
        cmd.ExecuteNonQuery()


    Else
        'update data in table
        cmd.CommandText = "UPDATE inventory  SET ID =" & Me.txtstdID.Text & ",BRAND='" & Me.cboBrand.Text & "', SPECIFICATION='" & Me.txtDescription.Text & "', STATUS = '" & strStat & "', WHERE ID=" & Me.txtstdID.Text & ""
        cmd.ExecuteNonQuery()
    End If
    'refresh data in list
    RefreshData()
    'clear form
    Me.btnClear.PerformClick()

    'close connection
    cnn.Close()


    Exit Sub
 ErrSQL:
    MsgBox(Err.Description)


End Sub
4

1 回答 1

3

缩短代码没有太多工作要做,防止 Sql Injection 和解析问题有很多工作要做。我会尝试将您的代码更改为此

Try
    Using cnn = new OleDbConnection(constring)
        Dim cmd As New OleDb.OleDbCommand
        cnn.Open()
        cmd.Connection = cnn
        Dim cmdText as String

        'check whether add new update
        If Me.txtstdID.Tag & "" = "" Then
              cmdText = "INSERT INTO inventory (ID,BRAND,SPECIFICATION,STATUS) " + 
                         "Values (@ID, @Brand, @specs, @stat)"
        else
              cmdText = "UPDATE inventory SET ID=@ID, BRAND=@Brand,SPECIFICATION=@specs" +
                        "STATUS = @stat WHERE ID=@ID"    
        End If
        cmd.CommandText = cmdText
        cmd.Parametes.AddWithValue("@ID", Me.txtstdID.Text)
        cmd.Parametes.AddWithValue("@Brand", Me.cboBrand.Text)
        cmd.Parametes.AddWithValue("@specs", Me.txtDescription.Text)
        cmd.Parametes.AddWithValue("@stat", strStat)
        cmd.ExecuteNonQuery()
   End Using
   'refresh data in list
   RefreshData()
   'clear form
   Me.btnClear.PerformClick()
Catch(x As Exception)
    MsgBox(x.Message)
End Try

我很想删除SET ID=@IDUpdate 语句中的冗余,但是,您必须在其他参数之后添加 @ID 参数,因为在 OleDb 中,参数顺序很重要

于 2013-03-01T09:47:59.967 回答