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
+18.6k Golang : Get download file size
+7.9k Golang : Gomobile init produce "iphoneos" cannot be located error
+9k Golang : Build and compile multiple source files
+10.1k Golang : How to tokenize source code with text/scanner package?
+14.3k Golang : Get uploaded file name or access uploaded files
+19.1k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+11.2k CodeIgniter : How to check if a session exist in PHP?
+20.6k Nginx + FastCGI + Go Setup.
+9.8k Golang : Resumable upload to Google Drive(RESTful) example
+7.7k Golang : get the current working directory of a running program
+4.7k Linux/MacOSX : How to symlink a file?