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

Golang sql.Rows类代码示例

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

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



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

示例1: ScanAll

/*
ScanAll accepts a pointer to a slice of a type and fills it with repeated calls to Scan.

ScanAll only works if you're trying to extract a single object from each row
of the query results. Additionally, it closes the passed sql.Rows object. ScanAll
effectively replaces this code

  // old code
  defer rows.Close()
  objs := []Object{}
  for rows.Next() {
	  var obj Object
	  Scan(rows, &obj)
	  objs = append(objs, obj)
  }

With simply

  // new code
  objs := []Object{}
  ScanAll(rows, &objs)
*/
func ScanAll(rows *sql.Rows, slicePtr interface{}) error {
	defer rows.Close()

	sliceVal := reflect.ValueOf(slicePtr).Elem()

	if sliceVal.Kind() != reflect.Slice {
		return fmt.Errorf("Argument to crud.ScanAll is not a slice")
	}

	elemType := sliceVal.Type().Elem()

	if elemType.Kind() != reflect.Struct {
		return fmt.Errorf("Argument to crud.ScanAll must be a slice of structs")
	}

	for rows.Next() {
		newVal := reflect.New(elemType)

		if er := Scan(rows, newVal.Interface()); er != nil {
			return er
		}

		sliceVal.Set(reflect.Append(sliceVal, newVal.Elem()))
	}

	return nil
}
开发者ID:bhaumikshah23,项目名称:crud,代码行数:49,代码来源:scan.go


示例2: scanUser

func scanUser(user *data.User, rows *sql.Rows) error {
	var createTimeString string

	err := rows.Scan(
		&user.Username,
		&user.Password,
		&user.Salt,
		&user.Role,
		&user.TrustLevel,
		&createTimeString,
	)

	if err != nil {
		return err
	}

	createTime, err := time.Parse("2006-01-02 15:04:05", createTimeString) // this assumes UTC as timezone

	if err != nil {
		log.Println("User scanner failed to parse time.")
		return err
	}

	user.CreateTime = createTime

	return nil
}
开发者ID:falahhaprak,项目名称:rter,代码行数:27,代码来源:scanners.go


示例3: scanItemComment

func scanItemComment(comment *data.ItemComment, rows *sql.Rows) error {
	var updateTimeString string

	err := rows.Scan(
		&comment.ID,
		&comment.ItemID,
		&comment.Author,
		&comment.Body,
		&updateTimeString,
	)

	if err != nil {
		return err
	}

	updateTime, err := time.Parse("2006-01-02 15:04:05", updateTimeString) // this assumes UTC as timezone

	if err != nil {
		log.Println("ItemComment scanner failed to parse time. " + updateTimeString)
		return err
	}

	comment.UpdateTime = updateTime

	return nil
}
开发者ID:falahhaprak,项目名称:rter,代码行数:26,代码来源:scanners.go


示例4: sexDomain

func sexDomain(dom string) (sexAnswer bool, err error) {
	var stmt *sql.Stmt

	stmt, err = db.Prepare(`SELECT dom FROM domains WHERE dom = $1 AND sex = true LIMIT 1`)

	if err != nil {
		fmt.Printf("db.Prepare error: %v\n", err)
		return false, err
	}

	var rows *sql.Rows

	rows, err = stmt.Query(dom)
	if err != nil {
		fmt.Printf("stmt.Query error: %v\n", err)
		return false, err
	}

	defer stmt.Close()
	if rows.Next() {
		var domain string

		err = rows.Scan(&domain)
		if err != nil {
			fmt.Printf("rows.Scan error: %v\n", err)
			return false, err
		}
		if configuration.Debug == "Yes" {
			fmt.Println("domain => \"" + domain + "\"")
		}
		return true, err
	}

	return false, nil
}
开发者ID:beemoboy,项目名称:squid-helpers,代码行数:35,代码来源:filtering_http_api.go


示例5: FetchRow

/*
	Copies *sql.Rows into the slice of maps or structs given by the pointer dst.
*/
func (self *T) FetchRow(dst interface{}, rows *sql.Rows) error {

	dstv := reflect.ValueOf(dst)

	if dstv.IsNil() || dstv.Kind() != reflect.Ptr {
		return db.ErrExpectingPointer
	}

	itemv := dstv.Elem()

	columns, err := getRowColumns(rows)

	if err != nil {
		return err
	}

	next := rows.Next()

	if next == false {
		return db.ErrNoMoreRows
	}

	item, err := self.fetchResult(itemv.Type(), rows, columns)

	if err != nil {
		return err
	}

	itemv.Set(reflect.Indirect(item))

	return nil
}
开发者ID:pzduniak,项目名称:db,代码行数:35,代码来源:main.go


示例6: One

func (scan *Scan) One(rows *sql.Rows) error {
	for rows.Next() {
		return scan.Scan(rows, meta.DirectValueOf(scan.To))
	}

	return errors.New("No matching rows found.")
}
开发者ID:rjp,项目名称:crud,代码行数:7,代码来源:scan.go


示例7: bmPreparedQuery

func bmPreparedQuery(b *testing.B) {
	stmt, err := db.Prepare("SELECT number, str FROM test")
	if err != nil {
		panic(err)
	}

	var num int64
	var str string
	var i int64
	var rows *sql.Rows
	for rep := 0; rep < 10000; rep++ {
		rows, err = stmt.Query()
		if err != nil {
			panic(err)
		}

		i = 0
		for rows.Next() {
			rows.Scan(&num, &str)
			if num != i {
				panic(fmt.Sprintf("Result didn't match: %d!=%d", num, i))
			}
			i++
		}

		if i != 100 {
			panic(fmt.Sprintf("Rows count doesn't match: %d!=100", i))
		}
	}

	stmt.Close()
}
开发者ID:viney,项目名称:go-db-driver,代码行数:32,代码来源:benchmark.go


示例8: scan

// Scan values from the database
func scan(cols []string, rows *sql.Rows) map[string]interface{} {

	var rtn = map[string]interface{}{}

	// Create scanner array
	var values []interface{}
	var generic = reflect.TypeOf(values).Elem()
	for i := 0; i < len(cols); i++ {
		values = append(values, reflect.New(generic).Interface())
	}

	// Scan!
	var err = rows.Scan(values...)
	if err != nil {
		n.Log("Driver failed to scan values: %s", err.Error())
		return nil
	}

	// Convert into native types
	for i := 0; i < len(cols); i++ {
		var raw_value = *(values[i].(*interface{}))
		var raw_type = reflect.TypeOf(raw_value)
		switch {
		case raw_type == reflect.TypeOf(int64(0)):
			rtn[cols[i]] = raw_value.(int64)
		}
	}

	return rtn
}
开发者ID:shadowmint,项目名称:go-worker,代码行数:31,代码来源:scanner.go


示例9: setTimer

func setTimer(rows *sql.Rows) (*Timer, error) {
	var finishedAt pq.NullTime
	var createdAt pq.NullTime

	timer := Timer{}

	err := rows.Scan(&timer.ID, &timer.User, &timer.Name, &createdAt, &finishedAt)
	if err != nil {
		return nil, err
	}

	val, err := createdAt.Value()
	if err != nil {
		return nil, err
	}

	if val != nil {
		timer.CreatedAt = &createdAt.Time
	}

	val, err = finishedAt.Value()
	if err != nil {
		return nil, err
	}

	if val != nil {
		timer.FinishedAt = &finishedAt.Time
	}

	return &timer, nil
}
开发者ID:gistia,项目名称:slackbot,代码行数:31,代码来源:timers.go


示例10: findNotesByUser

func findNotesByUser(user *User, query string) []*Note {
	var err error
	var rows *sql.Rows

	if len(query) == 0 {
		rows, err = db.Query("SELECT * FROM notes WHERE user_id=?", user.ID)
	} else {
		queryFmt := fmt.Sprintf("%%%s%%", query)
		rows, err = db.Query(
			"SELECT * FROM notes WHERE user_id=? AND (body LIKE ? OR title LIKE ?)",
			user.ID,
			queryFmt,
			queryFmt)
	}

	if err != nil {
		checkErr(err, "findNotesByUser")
	} else {
		defer rows.Close()
	}

	var notes []*Note
	for rows.Next() {
		notes = append(notes, noteFromDbRows(rows))
	}
	return notes
}
开发者ID:LastZactionHero,项目名称:graynote_server,代码行数:27,代码来源:note.go


示例11: List

//List ...
func (vs VictualService) List() []Victual {
	db, err := sql.Open("postgres", "host=localhost port=5432 user=pober dbname=pober sslmode=disable")
	checkErr(err)
	defer db.Close()

	var rows *sql.Rows
	rows, err = db.Query("SELECT id, description, brand, source, energyCal, energyJoule, fat, saturatedFat, carbohydrates, sugars, protein, salt, fiber, barCode, weightVolumeRatio FROM dc.victual")
	checkErr(err)

	victuals := []Victual{}

	for rows.Next() {
		var victual Victual
		err = rows.Scan(&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)
		victuals = append(victuals, victual)
	}
	return victuals
}
开发者ID:berka77,项目名称:diabetes-companion,代码行数:34,代码来源:victualservice.go


示例12: getCallRoutes

func getCallRoutes(lastNHours int, failedOnly bool) (callRoutes []*callRoute, err error) {
	var rows *sql.Rows
	callRouteSQL := `
      SELECT * FROM (
        SELECT c.app, c.route, COUNT(c.*) AS count, ROUND(AVG(extract(epoch from (c."end" - c.start))*1000000))::bigint AS avg_duration
        FROM "` + appmon.DBSchema + `".call c
        WHERE current_timestamp - c.start < ($1::int * interval '1 hour')
          AND c."end" IS NOT NULL
          AND ((NOT $2) OR (http_status_code < 200 OR http_status_code >= 400))
        GROUP BY app, route
      ) q ORDER BY count DESC
`
	rows, err = appmon.DB.Query(callRouteSQL, lastNHours, failedOnly)
	if err != nil {
		return nil, err
	}
	for rows.Next() {
		cr := new(callRoute)
		err = rows.Scan(&cr.App, &cr.Route, &cr.Count, &cr.AvgDuration)
		if err != nil {
			return
		}
		callRoutes = append(callRoutes, cr)
	}
	return
}
开发者ID:pombredanne,项目名称:appmon,代码行数:26,代码来源:ui.go


示例13: bindComponent

func bindComponent(name string, rs *sql.Rows, ctype componentType, manager *Manager) (*Component, error) {
	var id int64
	cols, err := rs.Columns()
	if err != nil {
		return nil, err
	}
	ifaces := make([]interface{}, len(cols))
	ifaceptrs := make([]interface{}, len(cols))
	for i := 0; i < len(ifaces); i++ {
		ifaceptrs[i] = &ifaces[i]
	}
	err = rs.Scan(ifaceptrs...)
	if err != nil {
		return nil, err
	}
	cv := reflect.New(ctype.typ).Elem()
	for i, field := range cols {
		if field == "entity_id" {
			id = ifaces[i].(int64)
			continue
		}
		f := cv.FieldByName(field)
		if !f.IsValid() {
			return nil, fmt.Errorf("Field %s is invalid for %s", field, name)
		}
		iv := reflect.ValueOf(ifaces[i])
		switch iv.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			f.SetInt(iv.Int())
		default:
			f.Set(iv)
		}
	}
	return &Component{entity: id, name: name, isNew: false, manager: manager, data: cv.Addr().Interface()}, nil
}
开发者ID:zuwiki,项目名称:spellbook,代码行数:35,代码来源:spellbook.go


示例14: Select

func (d DAO) Select(key interface{}, result interface{}) error {
	if d.conn == nil {
		return errors.New("no connection to mysql!")
	}

	var err error
	var rows *sql.Rows
	sql := fmt.Sprintf("select * from %s where id = %d", d.table, key)
	rows, err = d.conn.Query(sql)
	if err != nil {
		fmt.Println(err)
		return err
	}

	t := reflect.ValueOf(result)
	e := t.Elem()

	e = e.Slice(0, e.Len())
	i := 0
	for rows.Next() && i < e.Len() {
		j := 0
		s := make([]interface{}, 0, 10)
		for j < e.Index(i).NumField() {
			s = append(s, e.Index(i).Field(j).Addr().Interface())
			j++
			//fmt.Println(j)
		}
		err = rows.Scan(s...)
		i++
	}

	return err
}
开发者ID:hauerwu,项目名称:gotest,代码行数:33,代码来源:mysql.go


示例15: validate_result_of_sp

func validate_result_of_sp(dbt *DBTest, rows *sql.Rows) {

	// final OK packet , indicate last INSERT effected rows
	// https://dev.mysql.com/doc/internals/en/multi-resultset.html
	if res, ok := rows.Sibling(); false == ok {
		dbt.Fatal("there should be a last ok packet.")
	} else if nil == res {
		dbt.Fatal("last packet of CALL should return a Result.")
	} else {
		if affcted, err := res.RowsAffected(); nil != err {
			dbt.Fatal("should not return err when RowsAffected")
		} else if 1 != affcted {
			dbt.Fatal("Last INSERT STMT in SP should affected one row. ")
		}

		if insertId, err := res.LastInsertId(); nil != err {
			dbt.Fatal("should not return err when LastInsertId")
		} else if 0 != insertId {
			dbt.Fatalf("Last INSERT STMT in SP should not return LAST_INSERT_ID:%d ", insertId)
		}
		if true == rows.Next() {
			dbt.Fatal("last packet has no rows, but just affected rows and last insert id")
		}
	}

}
开发者ID:databasex,项目名称:mysql,代码行数:26,代码来源:multi_test.go


示例16: querySlice

// Query multiple rows into a slice.
func querySlice(model *model, slice interface{}, rows *sql.Rows) error {
	// var slice *[]T
	// sliceVal := *slice
	var (
		sliceVal = reflect.ValueOf(slice).Elem()
		foundCap = 0
		err      error
	)
	// first, populate the existing allocated elements in the slice. If it's an
	// empty slice, this loop will effectively be skipped.
	for i := 0; i < sliceVal.Len() && rows.Next(); i++ {
		if foundCap, err = model.scan(sliceVal.Index(i), rows, foundCap); err != nil {
			return err
		}
	}

	// now start scanning into new values and append to the slice. If we're
	// already done, this loop will effectively be skipped.
	// var sliceElemType type = T
	sliceElemType := sliceVal.Type().Elem()
	for rows.Next() {
		val := reflect.New(sliceElemType)
		if _, err := model.scan(val, rows, foundCap); err != nil {
			return err
		}
		sliceVal.Set(reflect.Append(sliceVal, val.Elem()))
	}

	return nil
}
开发者ID:moshee,项目名称:gas,代码行数:31,代码来源:models.go


示例17: Parse

//Parse an executed query
func (dbw *Sqlite3) Parse(rows *sql.Rows) (results Results, err error) {
	// here im not sure what im getting from the db as it can be anything from the results
	//therefore i wish i can just put everything in a bucket, and think later.
	tc, tn := dbw.TotalCount(rows)
	// multiFields := make([]interface{}, tc)
	multiFieldsPtrs := make([]interface{}, tc)
	for i := 0; i < tc; i++ {
		var multiFields interface{}
		multiFieldsPtrs[i] = &multiFields
	}

	headers := make(map[string]interface{})
	headers["fields"] = tn
	results = append(results, headers)
	for rows.Next() {
		err = rows.Scan(multiFieldsPtrs...)
		checkErrors(err)
		tempMap := make(map[string]interface{})
		for idx, label := range tn {
			row := *(multiFieldsPtrs[idx].(*interface{}))
			// if sizeOf(row) < 1 {
			// 	skip = true
			// 	break
			// }
			tempMap[label] = row
		}
		results = append(results, tempMap)
	}
	return
}
开发者ID:kennuzzo,项目名称:go-utils,代码行数:31,代码来源:sqliteWrapper.go


示例18: populateApplicationGuides

func populateApplicationGuides(rows *sql.Rows, ch chan []ApplicationGuide) {
	var ag ApplicationGuide
	var ags []ApplicationGuide
	var catID *int
	var icon []byte
	var catName *string
	for rows.Next() {
		err := rows.Scan(
			&ag.ID,
			&ag.Url,
			&ag.Website.ID,
			&ag.FileType,
			&catID,
			&icon,
			&catName,
		)
		if err != nil {
			ch <- ags
		}
		if catID != nil {
			ag.Category.CategoryID = *catID
		}
		if catName != nil {
			ag.Category.Title = *catName
		}
		if icon != nil {
			ag.Icon = string(icon[:])
		}
		ags = append(ags, ag)
	}
	ch <- ags
	return
}
开发者ID:ninnemana,项目名称:API,代码行数:33,代码来源:applicationGuide.go


示例19: ScanToStruct

func (scan *Scan) ScanToStruct(rows *sql.Rows, record reflect.Value) error {
	columns, err := rows.Columns()
	if err != nil {
		return err
	}

	values := make([]interface{}, len(columns))

	for i, column := range columns {
		var field reflect.Value

		fieldName := scan.SQLColumnDict[column]

		if scan.ToPointers {
			field = record.Elem().FieldByName(fieldName)
		} else {
			field = record.FieldByName(fieldName)
		}

		if field.IsValid() {
			values[i] = field.Addr().Interface()
		} else {
			values[i] = &values[i]
		}
	}

	return rows.Scan(values...)
}
开发者ID:rjp,项目名称:crud,代码行数:28,代码来源:scan.go


示例20: MItemSelectByID

func MItemSelectByID(db *sql.DB, itemID int) (*MItem, error) {
	q := `
select
	item_id
	,image_id
	,type
	,name
	,detail
	,param
from
	m_item
where
	item_id = $1
`
	var rows *sql.Rows
	var err error
	rows, err = db.Query(q, itemID)
	if err != nil {
		return nil, err
	}

	for rows.Next() {
		var mItem MItem
		if err := rows.Scan(&mItem.ItemID, &mItem.ImageID, &mItem.ItemType, &mItem.Name, &mItem.Detail, &mItem.Param); err != nil {
			fmt.Println(err)
		}
		return &mItem, nil
	}

	return nil, errors.New("not found")
}
开发者ID:kyokomi-sandbox,项目名称:sandbox,代码行数:31,代码来源:sql.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang sql.Stmt类代码示例发布时间:2022-05-24
下一篇:
Golang sql.Row类代码示例发布时间: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