• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang sql.Result类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中database/sql.Result的典型用法代码示例。如果您正苦于以下问题:Golang Result类的具体用法?Golang Result怎么用?Golang Result使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Result类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: 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
}
开发者ID:gpavlidi,项目名称:sample-go-website,代码行数:25,代码来源:user.go


示例2: 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)
}
开发者ID:narrowizard,项目名称:tinysql,代码行数:30,代码来源:builder.go


示例3: 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()
}
开发者ID:Zocprint,项目名称:go301,代码行数:27,代码来源:query.go


示例4: 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
}
开发者ID:berka77,项目名称:diabetes-companion,代码行数:36,代码来源:victualservice.go


示例5: 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
}
开发者ID:chenbk85,项目名称:nephele,代码行数:30,代码来源:config.go


示例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")
	}
}
开发者ID:0xbadjuju,项目名称:beam,代码行数:7,代码来源:generics.go


示例7: 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
}
开发者ID:GeoNet,项目名称:mtr,代码行数:31,代码来源:field_metric_tag.go


示例8: 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
}
开发者ID:yaolingling,项目名称:harbor,代码行数:29,代码来源:user.go


示例9: 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
}
开发者ID:go51,项目名称:mysql551,代码行数:31,代码来源:mysql551.go


示例10: 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
}
开发者ID:applepi-icpc,项目名称:icarus,代码行数:31,代码来源:driver.go


示例11: getAffectedRows

func (p *TxScope) getAffectedRows(r sql.Result) int64 {
	if count, err := r.RowsAffected(); err != nil {
		panic(err)
	} else {
		return count
	}
}
开发者ID:eynStudio,项目名称:gobreak,代码行数:7,代码来源:txscope.go


示例12: 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
}
开发者ID:JamesClonk,项目名称:go-todo,代码行数:31,代码来源:storage.go


示例13: 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
}
开发者ID:zhuharev,项目名称:storm,代码行数:30,代码来源:mysql.go


示例14: ExecSql

func (this *Database) ExecSql(mailbox rpc.Mailbox, msg *rpc.Message) (errcode int32, reply *rpc.Message) {
	var sqlstr string
	var callback string
	var callbackparams share.DBParams

	if server.Check(server.ParseArgs(msg, &sqlstr, &callback, &callbackparams)) {
		return 0, nil
	}

	sqlconn := db.sql
	var r sql.Result
	var err error

	app := server.GetAppById(mailbox.App)
	if app == nil {
		log.LogError(server.ErrAppNotFound)
		return 0, nil
	}

	if r, err = sqlconn.Exec(sqlstr); err != nil {
		log.LogError("sql:", sqlstr)
		server.Check(app.Call(nil, callback, callbackparams, 0, err.Error()))
		return 0, nil
	}

	eff, _ := r.RowsAffected()
	server.Check(app.Call(nil, callback, callbackparams, eff, ""))
	return 0, nil
}
开发者ID:mysll,项目名称:flynet,代码行数:29,代码来源:db_raw.go


示例15: 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()
}
开发者ID:itkpi,项目名称:journey,代码行数:28,代码来源:insertion.go


示例16: 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
	}
}
开发者ID:ying32,项目名称:YingBlog,代码行数:34,代码来源:db.go


示例17: 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

}
开发者ID:colefan,项目名称:myorm,代码行数:32,代码来源:db.go


示例18: 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
}
开发者ID:princeofdatamining,项目名称:golib,代码行数:29,代码来源:update.go


示例19: 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
}
开发者ID:lucmichalski,项目名称:fae,代码行数:33,代码来源:mysql.go


示例20: 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
}
开发者ID:princeofdatamining,项目名称:golib,代码行数:25,代码来源:update.go



注:本文中的database/sql.Result类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang sql.Row类代码示例发布时间:2022-05-24
下一篇:
Golang sql.NullString类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap