本文整理匯總了Golang中database/sql.Result.RowsAffected方法的典型用法代碼示例。如果您正苦於以下問題:Golang Result.RowsAffected方法的具體用法?Golang Result.RowsAffected怎麽用?Golang Result.RowsAffected使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類database/sql.Result
的用法示例。
在下文中一共展示了Result.RowsAffected方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: SetInc
/**
* SetInc
* @param fieldname string
* @param value int
* @return rows,error
*/
func (this *Sql) SetInc(field string, value int) (int64, error) {
sqlstr := " UPDATE " + this.tableName + " "
sqlstr += " SET "
field_filted := this.convertValue2String(field)
sqlstr += field_filted + " = " + field_filted + " + " + this.convertValue2String(value)
sqlstr += " WHERE "
sqlstr += this.conditionSql
//slimSqlLog("SETINC", 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 {
num, err := r.RowsAffected()
if err != nil {
return 0, err
} else {
return num, nil
}
}
}
示例2: 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
}
示例3: execUpdate
/* **
執行更新操作
param1 表名
param2 柱頭
parma3 條件
param4 參數
return 影響行數,錯誤
** */
func (self *MDB) execUpdate(tableName, cols, condition string, args ...interface{}) (int64, error) {
tx, err := self.Begin()
if err != nil {
return 0, err
}
if condition == "" || len(args) == 0 {
return 0, errors.New("條件和參數都不能為空!")
}
stmt, err := tx.Prepare(fmt.Sprintf("UPDATE %s SET %s WHERE %s", tableName, cols, condition))
if err != nil {
return 0, err
}
var result sql.Result
if result, err = stmt.Exec(args...); err != nil {
return 0, err
}
defer stmt.Close()
if err = tx.Commit(); err != nil {
return 0, err
}
if affected, err := result.RowsAffected(); err != nil {
return 0, err
} else {
return affected, nil
}
}
示例4: 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
}
示例5: Update
//Update ...
func (vs VictualService) Update(victual *Victual) *Victual {
db, err := sql.Open("postgres", "host=localhost port=5432 user=pober dbname=pober sslmode=disable")
checkErr(err)
defer db.Close()
var statement *sql.Stmt
statement, err = db.Prepare("UPDATE dc.victual SET description = $1, brand = $2, source = $3, energyCal = $4, energyJoule = $5, fat = $6, saturatedFat = $7, carbohydrates = $8, sugars = $9, protein = $10, salt = $11, fiber = $12, barCode = $13, weightVolumeRatio = $14 WHERE ID = $1")
checkErr(err)
var result sql.Result
result, err = statement.Exec(victual.ID,
victual.Description,
victual.Brand,
victual.Source,
victual.EnergyCal,
victual.EnergyJoule,
victual.Fat,
victual.SaturatedFat,
victual.Carbohydrates,
victual.Sugars,
victual.Protein,
victual.Salt,
victual.Fiber,
victual.BarCode,
victual.WeightVolumeRatio)
checkErr(err)
var rowsAffected int64
rowsAffected, err = result.RowsAffected()
checkErr(err)
statement.Close()
if rowsAffected == 1 {
return victual
}
return nil
}
示例6: check_result
func check_result(result sql.Result) {
rows, err := result.RowsAffected()
check_error(err)
if rows == 0 {
fmt.Printf("No rows affected by query")
}
}
示例7: CreateTables
func (database *Database) CreateTables(tableConf *TableConf) {
db, err := sql.Open(database.Driver, database.dataSource)
if err != nil {
panic(err)
}
var result sql.Result
var auto_increment_syntax = "INT AUTO INCREMENT "
if database.IsPostgres() {
auto_increment_syntax = "SERIAL "
}
fmt.Printf("creating table '%s'... \n", tableConf.Name)
query := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (id %s PRIMARY KEY, %s varchar(255), %s varchar(255), created_at timestamp DEFAULT CURRENT_TIMESTAMP, updated_at timestamp DEFAULT CURRENT_TIMESTAMP)", tableConf.Name, auto_increment_syntax, tableConf.Hash, tableConf.Url)
result, err = db.Exec(query)
if err != nil {
panic(err)
}
result.RowsAffected()
fmt.Printf("creating table 'goahead_statistics'... \n")
query = fmt.Sprintf("CREATE TABLE IF NOT EXISTS goahead_statistics (id %s PRIMARY KEY, created_at timestamp DEFAULT CURRENT_TIMESTAMP)", auto_increment_syntax)
result, err = db.Exec(query)
if err != nil {
panic(err)
}
result.RowsAffected()
}
示例8: BatchExec
func (d *DBAlias) BatchExec(sqlbuf string, argsv [][]interface{}) (affectedRows int64, err error) {
var result sql.Result
if argsv == nil || len(argsv) == 0 {
result, err = d.db.Exec(sqlbuf)
if err == nil {
affectedRows, err = result.RowsAffected()
}
return
} else {
var stmt *sql.Stmt
stmt, err = d.db.Prepare(sqlbuf)
if err != nil {
return
}
defer stmt.Close()
affectedRows = 0
for i, _ := range argsv {
r, err1 := stmt.Exec(argsv[i]...)
if err1 != nil {
err = err1
return
}
num, _ := r.RowsAffected()
affectedRows += num
}
}
return
}
示例9: Update2
func (this *tableMap) Update2(exec SQLExecutor, where string, data map[string]string, except []string) (rows int64, err error) {
dialect := this.dbmap.dialect
updSQL := dialect.UpdateSQL(this.schemaName, this.tableName)
//
L := len(data)
setFields := make([]string, L)
quote := ""
noQuotes := array2dict(except)
var i int
for key, val := range data {
if _, ok := noQuotes[key]; ok {
quote = ""
} else {
quote = "'"
}
setFields[i] = fmt.Sprintf("%s = %s%s%s", dialect.QuoteField(key), quote, val, quote)
i++
}
//
query := fmt.Sprintf(updSQL, strings.Join(setFields, ", "), setWhere(where))
if exec == nil {
exec = this
}
var res sql.Result
if res, err = exec.Exec(query); err == nil {
rows, err = res.RowsAffected()
}
return
}
示例10: update
func (this *tableMap) update(vptr reflect.Value, exec SQLExecutor, execVal []reflect.Value) (rows int64, err error) {
var (
bind *bindObj
res sql.Result
)
if err = triggerRun("PreUpdate", vptr, execVal); err != nil {
return
}
if bind, err = this.bindUpdate(); err != nil {
return
}
if err = bind.bindArgs(vptr.Elem()); err != nil {
return
}
if res, err = exec.Exec(bind.query, bind.argValues...); err != nil {
return
}
if rows, err = res.RowsAffected(); err != nil {
return
}
if err = triggerRun("PostUpdate", vptr, execVal); err != nil {
return
}
return
}
示例11: 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
}
示例12: fieldMetricTagPut
func fieldMetricTagPut(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result {
v := r.URL.Query()
var err error
var result sql.Result
if result, err = db.Exec(`INSERT INTO field.metric_tag(devicePK, typePK, tagPK)
SELECT devicePK, typePK, tagPK
FROM field.device, field.type, mtr.tag
WHERE deviceID = $1
AND typeID = $2
AND tag = $3`,
v.Get("deviceID"), v.Get("typeID"), v.Get("tag")); err != nil {
if err, ok := err.(*pq.Error); ok && err.Code == errorUniqueViolation {
// ignore unique constraint errors
return &weft.StatusOK
} else {
return weft.InternalServerError(err)
}
}
var i int64
if i, err = result.RowsAffected(); err != nil {
return weft.InternalServerError(err)
}
if i != 1 {
return weft.BadRequest("Didn't create row, check your query parameters exist")
}
return &weft.StatusOK
}
示例13: SetTasksStatus
/*
設置任務狀態
*/
func (this *TaskDao) SetTasksStatus(tasks []types.CrawlTask, status TaskStatus) (int64, error) {
nTasks := len(tasks)
var affectedRows int64 = 0
var err = ErrNoTasks
if nTasks > 0 {
taskIds := []int32{}
var result sql.Result
var args []interface{}
var sqlStr string
var now = time.Now()
for _, task := range tasks {
taskIds = append(taskIds, task.Id)
}
if status == TASK_FINISH {
sqlStr = fmt.Sprintf("update %s set status=%d, last_crawl_time=%d, crawl_times=crawl_times+1, update_time='%s' where id in (?)", TaskTable, status, now.Unix(), now.Format("2006-01-02 15:04:05"))
} else {
sqlStr = fmt.Sprintf("update %s set status=%d, update_time='%s' where id in (?)", TaskTable, status, now.Format("2006-01-02 15:04:05"))
}
sqlStr, args, err = sqlx.In(sqlStr, taskIds)
if err != nil {
log.Errorln("build sql to set task status failed! sql is ", sqlStr)
} else {
result, err = this.db.Exec(sqlStr, args...)
if err != nil {
log.Errorln("update tasks status error: ", err)
}
}
affectedRows, _ = result.RowsAffected()
}
return affectedRows, err
}
示例14: ChangeUserPassword
// ChangeUserPassword ...
func ChangeUserPassword(u models.User, oldPassword ...string) (err error) {
if len(oldPassword) > 1 {
return errors.New("Wrong numbers of params.")
}
o := GetOrmer()
var r sql.Result
if len(oldPassword) == 0 {
//In some cases, it may no need to check old password, just as Linux change password policies.
r, err = o.Raw(`update user set password=?, salt=? where user_id=?`, utils.Encrypt(u.Password, u.Salt), u.Salt, u.UserID).Exec()
} else {
r, err = o.Raw(`update user set password=?, salt=? where user_id=? and password = ?`, utils.Encrypt(u.Password, u.Salt), u.Salt, u.UserID, utils.Encrypt(oldPassword[0], u.Salt)).Exec()
}
if err != nil {
return err
}
c, err := r.RowsAffected()
if err != nil {
return err
}
if c == 0 {
return errors.New("No record has been modified, change password failed.")
}
return nil
}
示例15: getAffectedRows
func (p *TxScope) getAffectedRows(r sql.Result) int64 {
if count, err := r.RowsAffected(); err != nil {
panic(err)
} else {
return count
}
}