Wednesday, October 27, 2010

INSERT

The insert statement modifies the contents of the database in that we use it to create new records. By default, there is no data retrieved from the database as part of the operation. For this reason, we do not need to use a data adapter or dataset.

The INSERT SQL Statement

INSERT INTO TableName (FieldName1, FieldName2) VALUES (@FieldName1, @FieldName2)

Inserts data into the specified fields, creating a new record. Note that parameters are used to pass the values that need to be inserted into the fields.

Note the following code sample:

Public Sub insertIntoCart(ProductID As Integer, Quantity As Integer)
        

    Dim myConn As SqlConnection = New SqlConnection(MyConnString)
    myConn.Open()
    Dim strSQL As String = "INSERT INTO XYZCart (ProductID, Quantity, CustomerID) VALUES (@ProductID, @Quantity, @CustomerID)"
    Dim myComm As SqlCommand = New SqlCommand(strSQL, myConn)
    myComm.Parameters.AddWithValue("@ProductID", ProductID)
    myComm.Parameters.AddWithValue("@Quantity", ProductID)
    myComm.Parameters.AddWithValue("@CustomerID", 0)
    myComm.ExecuteNonQuery()
    myConn.Close()



End Sub

Parameters are used to pass the data for insertion. Note that they are passed to the AddWithValue method in the order they are specified in the SQL statement.

Also note, the ExecuteNonQuery method of the command object is engaged to complete the operation. This is common to the insert, update & delete operations.

No comments:

Post a Comment