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.8k Golang : Random integer with rand.Seed() within a given range
+12.4k Golang : Search and extract certain XML data example
+11.3k Golang : How to flush a channel before the end of program?
+7.7k Gogland : Where to put source code files in package directory for rookie
+6.5k Golang : Handling image beyond OpenCV video capture boundary
+30.4k Golang : How to redirect to new page with net/http?
+5k Golang : Constant and variable names in native language
+22.8k Golang : untar or extract tar ball archive example
+7.8k Golang : Getting Echo framework StartAutoTLS to work
+16.3k Golang :Trim white spaces from a string
+11.7k Golang : Gorilla web tool kit secure cookie example
+34.6k Golang : How to stream file to client(browser) or write to http.ResponseWriter?