Golang database/sql.Prepare function examples
package database/sql
Prepare creates a prepared statement for use within a transaction.
The returned statement operates within the transaction and can no longer be used once the transaction has been committed or rolled back.
To use an existing prepared statement on this transaction, see Tx.Stmt.
Golang database/sql.Prepare function usage examples
Example 1:
createCategory = "INSERT INTO BlogCategories (name,slug,active) VALUES (?,?,?)"
func (c *Category) Create() error {
db, err := sql.Open("mysql", database.ConnectionString())
if err != nil {
return err
}
defer db.Close()
tx, err := db.Begin()
if err != nil {
return err
}
stmt, err := tx.Prepare(createCategory)
res, err := stmt.Exec(c.Name, c.Slug, c.Active)
if err != nil {
tx.Rollback()
return err
}
id, err := res.LastInsertId()
c.ID = int(id)
if err != nil {
tx.Rollback()
return err
}
tx.Commit()
return nil
}
Example 2:
stmt, err := tx.Prepare(`insert or replace into plusplus (nick, score) values (?, ?)`)
if err != nil {
fmt.Printf("Database error: %v\n", err)
return
}
Reference :
Advertisement
Something interesting
Tutorials
+21.9k Golang : Use TLS version 1.2 and enforce server security configuration over client
+20.6k Golang : Secure(TLS) connection between server and client
+5.2k Golang : Calculate half life decay example
+15.2k Golang : How to add color to string?
+4.9k Javascript : How to get width and height of a div?
+13.2k Golang : Convert(cast) int to int64
+17.6k Golang : Upload/Receive file progress indicator
+6.3k Golang : How to get capacity of a slice or array?
+5.1k Golang : Display packages names during compilation
+10.4k Golang : cannot assign type int to value (type uint8) in range error
+13k Golang : Get terminal width and height example
+13.6k Golang : Strings comparison