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
+11.5k Golang : Generate DSA private, public key and PEM files example
+12.6k Golang : Exit, terminating or aborting a program
+52.6k Golang : How to get struct field and value by name
+20.7k Android Studio : AlertDialog and EditText to get user string input example
+9.1k Golang : Intercept and compare HTTP response code example
+18.6k Golang : Generate thumbnails from images
+6.5k Grep : How to grep for strings inside binary data
+17.6k Convert JSON to CSV in Golang
+24k Golang : Call function from another package
+17.3k Golang : How to tell if a file is compressed either gzip or zip ?
+9k Golang : Build and compile multiple source files
+9.4k Golang : Timeout example