本文整理匯總了Golang中github.com/jmoiron/sqlx.DB.Beginx方法的典型用法代碼示例。如果您正苦於以下問題:Golang DB.Beginx方法的具體用法?Golang DB.Beginx怎麽用?Golang DB.Beginx使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/jmoiron/sqlx.DB
的用法示例。
在下文中一共展示了DB.Beginx方法的2個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Create
// Create a new user in the database.
func (u *User) Create(db *sqlx.DB, fidT FlexIDType, fid string) error {
// Create the password hash
hpw, err := bcrypt.GenerateFromPassword([]byte(u.Password), 10)
if err != nil {
return err
}
tx, err := db.Beginx()
if err != nil {
return err
}
q := `INSERT INTO users (name, email, password, locationid, admin)
VALUES ($1, $2, $3, 0, $4)
RETURNING id`
var uid uint64
err = tx.QueryRowx(q, u.Name, u.Email, hpw, u.Admin).Scan(&uid)
if err != nil && err.Error() ==
`pq: duplicate key value violates unique constraint "users_email_key"` {
_ = tx.Rollback()
return err
}
if uid == 0 {
_ = tx.Rollback()
return err
}
q = `INSERT INTO userflexids (userid, flexid, flexidtype)
VALUES ($1, $2, $3)`
_, err = tx.Exec(q, uid, u.Email, 1)
if err != nil {
_ = tx.Rollback()
return err
}
_, err = tx.Exec(q, uid, fid, 2)
if err != nil {
_ = tx.Rollback()
return err
}
if err = tx.Commit(); err != nil {
return err
}
u.ID = uid
return nil
}
示例2: upload
func upload(resource io.Reader, db *sqlx.DB, repeat int) {
var feed Feed
if err := xml.NewDecoder(resource).Decode(&feed); err != nil {
log.Fatalf("cannot decode resource: %s", err)
}
tx, err := db.Beginx()
if err != nil {
log.Fatalf("cannot start transaction :%s", err)
}
defer tx.Rollback()
for i := 0; i < repeat; i++ {
for _, e := range feed.Entries {
var tid uint
err = tx.Get(&tid, `
INSERT INTO topics (title, author_id, created, updated, category_id)
VALUES ($1, $2, $3, $3, 1)
RETURNING topic_id
`, e.Title, 1, e.Updated)
if err != nil {
log.Fatalf("cannot insert topic: %s", err)
}
_, err = tx.Exec(`
INSERT INTO messages (topic_id, author_id, content, created)
VALUES ($1, $2, $3, $4)
`, tid, 1, e.Summary, e.Updated)
if err != nil {
log.Fatalf("cannot insert message: %s", err)
}
}
}
if err := tx.Commit(); err != nil {
log.Fatalf("cannot commit transaction: %s", err)
}
}