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
+23.2k Golang : Print out struct values in string format
+8.3k Swift : Convert (cast) Character to Integer?
+6.7k Golang : Experimental emojis or emoticons icons programming language
+5.7k Golang : Frobnicate or tweaking a string example
+28.8k Golang : Detect (OS) Operating System
+35.9k Golang : Integer is between a range
+10.2k Golang : How to profile or log time spend on execution?
+19.9k Golang : Count JSON objects and convert to slice/array
+14k Golang : concatenate(combine) strings
+5.8k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+10.9k Golang : How to transmit update file to client by HTTP request example
+8k Golang : What fmt.Println() can do and println() cannot do