Insert/Update/Delete Data Using ExecuteNonQuery

Unlike DataReader, ExecuteNonQuery function allows you to insert, update, and delete data. It executes a query that does not return any value. Consider the following example:
  1. 'Execute Non Query
  2. Public Function ExecNonQuery(ByVal strSQL As String)
  3. Dim conn As OleDbConnection
  4. conn = New OleDbConnection
  5.  
  6. Try
  7. With conn
  8. If .State = ConnectionState.Open Then .Close()
  9.  
  10. .ConnectionString = cnString
  11. .Open()
  12. End With
  13.  
  14. Dim cmd As OleDbCommand = New OleDbCommand(strSQL, conn)
  15.  
  16. cmd.ExecuteNonQuery()
  17.  
  18. Return True
  19. Catch ex As OleDbException
  20. MsgBox(ex.ToString)
  21.  
  22. Return False
  23. Finally
  24. conn.Close()
  25. End Try
  26. End Function
We use function in this code to determine if the query executes without error. Those it returns TRUE if no error occurs, or FALSE if it catches any error. Here’s an example to call this function:
  1. ExecNonQuery(“INSERT INTO Table1 (Field1, Field2, Field2) VALUES (‘Value1’, ‘Value2’, ‘Value3’);)

Tags

Add new comment