本文整理匯總了Golang中database/sql.Result.LastInsertId方法的典型用法代碼示例。如果您正苦於以下問題:Golang Result.LastInsertId方法的具體用法?Golang Result.LastInsertId怎麽用?Golang Result.LastInsertId使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類database/sql.Result
的用法示例。
在下文中一共展示了Result.LastInsertId方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Insert
// Insert 向指定table插入數據
func (this *builder) Insert(table string, model interface{}) int {
query := "insert into `" + table + "`"
value := reflect.ValueOf(model).Elem()
data := make(map[string]interface{})
mapStructToMap(value, data)
keys := " ("
values := " ("
params := make([]interface{}, 0, 0)
for k, v := range data {
keys += "`" + k + "`,"
values += "?,"
params = append(params, v)
}
query += keys[:len(keys)-1] + ") values"
query += values[:len(values)-1] + ")"
var result sql.Result
var err error
this.reset()
result, err = this.db.Exec(query, params...)
if err != nil {
return -1
}
var id int64
id, err = result.LastInsertId()
if err != nil {
return -1
}
return int(id)
}
示例2: InsertPost
func InsertPost(title []byte, slug string, markdown []byte, html []byte, featured bool, isPage bool, published bool, image []byte, created_at time.Time, created_by int64) (int64, error) {
status := "draft"
if published {
status = "published"
}
writeDB, err := readDB.Begin()
if err != nil {
writeDB.Rollback()
return 0, err
}
var result sql.Result
if published {
result, err = writeDB.Exec(stmtInsertPost, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), title, slug, markdown, html, featured, isPage, status, image, created_by, created_at, created_by, created_at, created_by, created_at, created_by)
} else {
result, err = writeDB.Exec(stmtInsertPost, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), title, slug, markdown, html, featured, isPage, status, image, created_by, created_at, created_by, created_at, created_by, nil, nil)
}
if err != nil {
writeDB.Rollback()
return 0, err
}
postId, err := result.LastInsertId()
if err != nil {
writeDB.Rollback()
return 0, err
}
return postId, writeDB.Commit()
}
示例3: Exec
func (m *Mysql) Exec(query string, param ...interface{}) (rowsAffected int64, lastInsertId int64) {
if !m.IsOpen() {
panic(errors.New("[mysql555]It is not connected to the host"))
}
var res sql.Result = nil
var err error = nil
if m.IsTransaction() {
res, err = m.tx.Exec(query, param...)
} else {
res, err = m.db.Exec(query, param...)
}
if err != nil {
message := err.Error()
message = message + "\n" + "[ SQL ] " + query + "\n" + fmt.Sprintf("[ PRM ] %#v\n", param)
panic(errors.New(message))
}
lastInsertId, err = res.LastInsertId()
if err != nil {
panic(err)
}
rowsAffected, err = res.RowsAffected()
if err != nil {
panic(err)
}
return
}
示例4: Insert
func (this *Config) Insert() error {
this.Recordtime = getNow()
var (
err error
id int64
res sql.Result
)
if this.Cat != nil {
tran := this.Cat.NewTransaction(DBTITLE, "Config.Insert")
defer func() {
if err != nil {
tran.SetStatus(err)
} else {
tran.SetStatus("0")
}
tran.Complete()
}()
}
o := orm.NewOrm()
res, err = o.Raw("INSERT INTO config(channelCode,`key`,value,recordTime)VALUES(?,?,?,?)", this.ChannelCode, this.Key, this.Value, this.Recordtime).Exec()
if err != nil {
return err
}
id, err = res.LastInsertId()
if err != nil {
return err
}
this.Id = id
return nil
}
示例5: Save
func (a *Account) Save() error {
db, err := connect()
if err != nil {
return err
}
defer db.Close()
stmt, err := db.Prepare("insert or replace into T_ACCOUNTS (ID, NAME, EMAIL, PASSWORD, SALT, ROLE, LAST_AUTH) values (?,?,?,?,?,?,?)")
if err != nil {
return err
}
defer stmt.Close()
var result sql.Result
if a.Id < 1 {
result, err = stmt.Exec(nil, a.Name, a.Email, a.Password, a.Salt, a.Role, a.LastAuth)
} else {
result, err = stmt.Exec(a.Id, a.Name, a.Email, a.Password, a.Salt, a.Role, a.LastAuth)
}
if err != nil {
return err
}
id, err := result.LastInsertId()
if err != nil {
return err
}
a.Id = int(id)
return nil
}
示例6: Exec
func (this *mysql) Exec(query string, args ...interface{}) (afftectedRows int64,
lastInsertId int64, err error) {
if this.db == nil {
return 0, 0, ErrNotOpen
}
if this.breaker.Open() {
return 0, 0, ErrCircuitOpen
}
var result sql.Result
result, err = this.db.Exec(query, args...)
if err != nil {
if this.isSystemError(err) {
log.Warn("mysql exec breaks: %s", err.Error())
this.breaker.Fail()
}
return 0, 0, err
}
afftectedRows, err = result.RowsAffected()
if err != nil {
if this.isSystemError(err) {
log.Warn("mysql exec2 breaks: %s", err.Error())
this.breaker.Fail()
}
} else {
this.breaker.Succeed()
}
lastInsertId, _ = result.LastInsertId()
return
}
示例7: CreateTask
// task.ID will be ignored.
func CreateTask(task icarus.TaskData) (ID int, err error) {
InitStorage()
var res sql.Result
res, err = db.Exec("INSERT INTO task (handle) VALUES (?)", task.Handle)
if err != nil {
log.Warnf("storage.CreateTask(): Failed to insert task %v: %s.", task, err.Error())
return
}
newID, err := res.LastInsertId()
if err != nil {
log.Warnf("storage.CreateTask(): Failed to get ID for task %v: %s.", task, err.Error())
}
ID = int(newID)
_, err = db.Exec("INSERT INTO user (userid, password, task_id) VALUES (?, ?, ?)", task.User.UserID, task.User.Password, ID)
if err != nil {
log.Warnf("storage.CreateTask(): Failed to insert user for task %v: %s.", task, err.Error())
return
}
for _, c := range task.Courses {
_, err = db.Exec("INSERT INTO course (name, desc, token, task_id) VALUES (?, ?, ?, ?)", c.Name, c.Desc, c.Token, ID)
if err != nil {
log.Warnf("storage.CreateTask(): Failed to insert course %v for task %v: %s.", c, task, err.Error())
return
}
}
return
}
示例8: AddUser
// POST /api/users
func (mgr *Manager) AddUser(w http.ResponseWriter, r *http.Request, rnd render.Render) {
req := make(map[string]string)
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil || len(req["name"]) < 3 || len(req["password"]) < 3 {
w.WriteHeader(400)
return
}
passwd, err := bcrypt.GenerateFromPassword([]byte(req["password"]), 11)
if err != nil {
log.Error("bcrypt.GenerateFromPassword: ", err)
w.WriteHeader(500)
return
}
var (
result sql.Result
id int64
)
result, err = mgr.db.Exec("insert into users (name, password) values(?,?)", req["name"], passwd)
if err == nil {
id, err = result.LastInsertId()
}
if err != nil {
mgr.showError(err, w)
return
}
rnd.JSON(200, map[string]interface{}{"name": req["name"], "id": id})
}
示例9: Create
func (self *MysqlDriver) Create(container string, query driver.Query) (id interface{}, requestError error) {
fmt.Println("mysql driver create:", container, query)
// Create mysql insert string from given query
var (
queryFields []string
queryValues []string
)
for k, v := range query {
fmt.Println("key/value:", k, v)
// TODO: check for sql injection
queryFields = append(queryFields, k)
queryValues = append(queryValues, fmt.Sprintf("'%s'", v))
}
fmt.Println("fields:", queryFields)
fmt.Println("values:", queryValues)
var result sql.Result
if result, requestError = self.db.Exec(fmt.Sprintf("INSERT INTO `users`(%s) VALUES(%s)", strings.Join(queryFields, ","), strings.Join(queryValues, ","))); requestError != nil {
// Failure
return
} else {
// Success
if id, requestError = result.LastInsertId(); requestError != nil {
// Failure
return
}
}
// Success
fmt.Println("success?:", id, requestError)
return
}
示例10: NewOrUpdateUser
func NewOrUpdateUser(db *sql.DB, user *User) error {
var err error
var res sql.Result
if user.Id == "" {
res, err = db.Exec("INSERT INTO users(firstName, lastName) VALUES(?,?)", user.FirstName, user.LastName)
} else {
res, err = db.Exec("UPDATE users SET firstName=?, lastName=? WHERE id=?", user.FirstName, user.LastName, user.Id)
}
if err != nil {
return err
}
lastId, err := res.LastInsertId()
if err != nil {
return err
}
rowCnt, err := res.RowsAffected()
if err != nil {
return err
}
if rowCnt != 1 {
return errors.New(fmt.Sprintf("Row count (%s) and/or lastId (%s) are wrong.", lastId, rowCnt))
}
return nil
}
示例11: exec
// Execute an sql 'exec' that returns 'insert ids' (api is stupid)
func (self *sql) exec(query string, columns []string, values ...[]interface{}) (*rowset, error) {
var output gsql.Result = nil
var err error = nil
// Pass params over
if len(values) > 0 {
output, err = self.db.Exec(query, values[0]...)
} else {
output, err = self.db.Exec(query)
}
if err != nil {
return nil, utils.Fail(1, "Error perfroming explicit SQL query \"%s\": %s", query, err.Error())
}
// Process output
var rtn = newRowset(nil).(*rowset)
var id, id_err = output.LastInsertId()
if id_err == nil {
var record = map[string]interface{}{}
for _, c := range columns {
record[c] = id
}
rtn.Values.PushBack(record)
}
return rtn, err
}
示例12: Add
/**
* Insert / convert ""/'' maybe a bug.
* @param map of data
* @return id,err
*/
func (this *Sql) Add(data map[string]interface{}) (int64, error) {
var columns []string
var values []string
for k, v := range data {
columns = append(columns, k)
tmp_v := this.convertValue2String(v)
values = append(values, "\""+tmp_v+"\"")
}
sqlstr := " INSERT INTO `" + this.tableName + "` " + " (" + strings.Join(columns, ",") + ") VALUES (" + strings.Join(values, ",") + ") "
//slimSqlLog("Insert", sqlstr)
var r sql.Result
var err error
if this.tx != nil {
r, err = this.tx.Exec(sqlstr)
} else {
r, err = this.getDbW().Exec(sqlstr)
}
if err != nil {
slimSqlLog("ERROR", sqlstr)
return 0, err
} else {
id, err := r.LastInsertId()
if err != nil {
return 0, err
} else {
return id, nil
}
}
}
示例13: registerMembers
func registerMembers() (err error) {
members := []Member{
{Name: "ミク", Birthday: "10/19", Bloodtype: "AB", Hobby: "ショッピング"},
{Name: "マホ", Birthday: "1/8", Bloodtype: "AB", Hobby: "漫畫"},
{Name: "コヒメ", Birthday: "11/24", Bloodtype: "O", Hobby: "ゲーム"},
}
stmt, err := Db.Prepare(`
INSERT INTO member (name, birthday, blood_type, hobby)
VALUES (?, ?, ?, ?)
`)
if err != nil {
return
}
defer stmt.Close()
for _, m := range members {
var ret sql.Result
ret, err = stmt.Exec(m.Name, m.Birthday, m.Bloodtype, m.Hobby)
if err != nil {
return
}
var id int64
id, err = ret.LastInsertId()
if err != nil {
return
}
m.Id = int(id)
fmt.Printf("Inserted. ID = %d, Name = %s\n", m.Id, m.Name)
}
return
}
示例14: NextSequence
func (dbSeq *SequenceDB) NextSequence() (sequence uint64, err error) {
var stmt *sql.Stmt
stmt, err = dbSeq.db.Prepare(`REPLACE INTO sequence(stub) VALUES ("sequence")`)
if err != nil {
log.Printf("sequence db prepare error. %v", err)
return 0, err
}
defer stmt.Close()
var res sql.Result
res, err = stmt.Exec()
if err != nil {
log.Printf("sequence db replace into error. %v", err)
return 0, err
}
// 兼容LastInsertId方法的返回值
var lastID int64
lastID, err = res.LastInsertId()
if err != nil {
log.Printf("sequence db get LastInsertId error. %v", err)
return 0, err
} else {
sequence = uint64(lastID)
// mysql sequence will start at 1, we actually want it to be
// started at 0. :)
sequence -= 1
return sequence, nil
}
}
示例15: hostRowFromSqlResult
func (h *Host) hostRowFromSqlResult(tx *sqlx.Tx, sqlResult sql.Result) (*HostRow, error) {
hostId, err := sqlResult.LastInsertId()
if err != nil {
return nil, err
}
return h.GetByID(tx, hostId)
}