Running SQL statements
After acquiring an instance of *sql.DB
, you can run SQL statements to modify or query data. These queries are simply SQL strings, but the flavor of SQL varies between database vendors.
Running SQL statements without explicit transactions
When interacting with a database, an important consideration is determining transaction boundaries. If you need to perform a single operation, such as inserting a row or running a query, you usually do not need to create a transaction explicitly. You can execute a single SQL statement that will start and end the transaction. However, if you have multiple SQL statements that should either run as an atomic unit or not run at all, you have to use a transaction.
How to do it...
- To run a SQL statement to update data, use
DB.Exec
orDB.ExecContext
:result, err:=db.ExecContext(ctx,`UPDATE users SET user.last_login=? WHERE user_id=?",time.Now(), userId) if err!=nil { // Handle error } n, err:=result.RowsAffected...