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
+15.9k Golang : Get file permission
+6.5k PHP : Shuffle to display different content or advertisement
+11.5k Golang : Generate DSA private, public key and PEM files example
+21.6k Golang : GORM create record or insert new record into database example
+4.7k Unix/Linux : How to pipe/save output of a command to file?
+6k Golang : Function as an argument type example
+19.3k Golang : Calculate entire request body length during run time
+26.4k Golang : Get executable name behind process ID example
+16.8k Golang : Get own process identifier
+5.2k Golang : Experimental Jawi programming language
+6.3k Unix/Linux : Use netstat to find out IP addresses served by your website server
+21.8k SSL : How to check if current certificate is sha1 or sha2