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
+8.2k Golang : Routes multiplexer routing example with regular expression control
+27.9k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+17k Golang : How to save log messages to file?
+13k Golang : Get terminal width and height example
+18.8k Golang : How to make function callback or pass value from function as parameter?
+23.7k Find and replace a character in a string in Go
+22.2k Golang : Convert seconds to minutes and remainder seconds
+12.9k Golang : Convert IPv4 address to packed 32-bit binary format
+7.7k Golang : get the current working directory of a running program
+11.7k Golang : How to detect a server/machine network interface capabilities?
+18.5k Golang : Aligning strings to right, left and center with fill example
+6.7k Golang : Derive cryptographic key from passwords with Argon2