本文整理汇总了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)
}
}