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
+16.3k Golang : How to extract links from web page ?
+16.5k Golang : Get IP addresses of a domain name
+8.3k Golang : Number guessing game with user input verification example
+5.5k Clean up Visual Studio For Mac installation failed disk full problem
+15.6k Golang : How to convert(cast) IP address to string?
+11.6k SSL : The certificate is not trusted because no issuer chain was provided
+5.2k JavaScript/JQuery : Redirect page examples
+4.5k Java : Generate multiplication table example
+4.6k Linux : sudo yum updates not working
+14.3k Golang : How to shuffle elements in array or slice?
+6.7k Golang : When to use make or new?
+22.2k Golang : Convert seconds to minutes and remainder seconds