Asp.Net – Adding Parameters to CommandType.Text

This is how you add parameters to a standard CommandType.Text SQL call.

This should prevent sql injection attacks.

        Using conSQL = New SqlConnection("CONNECTION STRING TO DATABASE")
                str = "SELECT * FROM TableName where customerid = @CustomerID and CartType = @CartType"
                cmdSQL = New SqlCommand(str, conSQL)
                cmdSQL.CommandType = CommandType.Text
                cmdSQL.Parameters.AddWithValue("@CustomerID", CustomerID)
                cmdSQL.Parameters.AddWithValue("@CartType", cartType)
                cartcount = cmdSQL.ExecuteScalar()
            Catch ex As Exception
                cartcount = 0
            End Try
        End Using