本文整理汇总了Golang中database/sql.Rows.Next方法的典型用法代码示例。如果您正苦于以下问题:Golang Rows.Next方法的具体用法?Golang Rows.Next怎么用?Golang Rows.Next使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类database/sql.Rows
的用法示例。
在下文中一共展示了Rows.Next方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Test_Query
func Test_Query(t *testing.T) {
conn, err := sql.Open("mysql", TestConnParam)
unitest.NotError(t, err)
defer conn.Close()
var res *sql.Rows
res, err = conn.Query("SELECT * FROM test ORDER BY id ASC")
unitest.NotError(t, err)
defer res.Close()
i := 0
for res.Next() {
var (
id int64
value string
)
err := res.Scan(&id, &value)
unitest.NotError(t, err)
unitest.Pass(t, id == int64(i))
unitest.Pass(t, value == strconv.Itoa(i))
i++
}
unitest.Pass(t, i == 10)
}
示例2: GetServiceAgentList
func (persister *Persister) GetServiceAgentList(cond string) ([]ServiceAgent, error) {
var rows *sql.Rows
var err error
if cond == "" {
rows, err = persister.Db.Query("SELECT service_host,docker_host,docker_port,is_active,perf_factor,ping_interval_secs,last_ping,exec_command,exec_args,portbinding_min,portbinding_max,portbindings FROM serviceagents")
} else {
rows, err = persister.Db.Query("SELECT service_host,docker_host,docker_port,is_active,perf_factor,ping_interval_secs,last_ping,exec_command,exec_args,portbinding_min,portbinding_max,portbindings FROM serviceagents where " + cond)
}
if err != nil {
return nil, err
}
defer rows.Close()
var serviceagents []ServiceAgent
i := 0
for rows.Next() {
serviceagent := ServiceAgent{}
var timevalue interface{}
rows.Scan(&serviceagent.ServiceHost, &serviceagent.DockerHost, &serviceagent.DockerPort, &serviceagent.IsActive, &serviceagent.PerfFactor, &serviceagent.KeepAlive, &timevalue, &serviceagent.ExecCommand, &serviceagent.ExecArgs, &serviceagent.Portbind_min, &serviceagent.Portbind_max, &serviceagent.Portbindings)
switch timevalue.(type) {
case string:
serviceagent.LastPing, err = time.Parse("2006-01-02 15:04:05 ", timevalue.(string))
case time.Time:
serviceagent.LastPing = timevalue.(time.Time)
}
if err != nil {
log.Println("error reading row ", err)
}
serviceagents = append(serviceagents, serviceagent)
i = i + 1
}
return serviceagents, nil
}
示例3: GetResultsTwo
func GetResultsTwo(rows *sql.Rows) [][]string {
var (
results [][]string
//result [][]string
id string
types string
title string
message string
i int
)
results = make([][]string, 1)
i = 0
for rows.Next() {
err := rows.Scan(&id, &types, &title, &message)
if err != nil {
//fmt.Println(err)
}
messages := []string{id, types, title, message}
fmt.Println(messages)
for index, element := range messages {
results[i][index] = element
}
i++
}
return results
}
示例4: PageJson
// sql_ := fmt.Sprintf(`SELECT "Json" %s where `+p.wheresql, p.getFrom())
// var rows *sql.Rows
// if rows, p.Err = p._query(sql_, p.whereargs...); p.NotErr() {
// defer rows.Close()
// for rows.Next() {
// var v []byte
// rows.Scan(&v)
// obj := reflect.New(p.model.Type).Interface()
// json.Unmarshal(v, obj)
// slicev = reflect.Append(slicev, reflect.ValueOf(obj).Elem())
// }
// resultv.Elem().Set(slicev.Slice(0, slicev.Len()))
// }
// return p
//}
func (p *Scope) PageJson(lst T, page, perPage int) (pager db.Paging) {
p.checkModel(lst)
pf := filter.NewPageFilter(page, perPage)
p.Limit(pf.Skip(), perPage)
pager.Total = p.Count(lst)
// log.Println(pager.Total)
resultv := reflect.ValueOf(lst)
if resultv.Kind() != reflect.Ptr || resultv.Elem().Kind() != reflect.Slice {
panic("out argument must be a slice address")
}
slicev := resultv.Elem()
wsa := p.buildWhere()
pas := p.buildPage()
sql_ := fmt.Sprintf(`SELECT "Json" %s `+wsa.Sql+" "+pas.Sql, p.getFrom())
var rows *sql.Rows
if rows, p.Err = p._query(sql_, wsa.Args...); p.NotErr() {
defer rows.Close()
for rows.Next() {
var v []byte
rows.Scan(&v)
obj := reflect.New(p.model.Type).Interface()
json.Unmarshal(v, obj)
slicev = reflect.Append(slicev, reflect.ValueOf(obj).Elem())
}
resultv.Elem().Set(slicev.Slice(0, slicev.Len()))
}
pager.Items = lst
// log.Println(lst)
return
}
示例5: 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
}
示例6: getNextChatArchivesId
func (gkDbCon *GkDbConDef) getNextChatArchivesId() (int32, *gkerr.GkErrDef) {
var stmt *sql.Stmt
var err error
stmt, err = gkDbCon.sqlDb.Prepare("select nextval('chat_archives_seq')")
if err != nil {
return 0, gkerr.GenGkErr("sql.Prepare"+getDatabaseErrorMessage(err), err, ERROR_ID_PREPARE)
}
defer stmt.Close()
var rows *sql.Rows
rows, err = stmt.Query()
if err != nil {
return 0, gkerr.GenGkErr("stmt.Query"+getDatabaseErrorMessage(err), err, ERROR_ID_QUERY)
}
defer rows.Close()
var id int32
if rows.Next() {
err = rows.Scan(&id)
if err != nil {
return 0, gkerr.GenGkErr("rows.Scan"+getDatabaseErrorMessage(err), err, ERROR_ID_ROWS_SCAN)
}
} else {
return 0, gkerr.GenGkErr("select users", nil, ERROR_ID_NO_ROWS_FOUND)
}
return id, nil
}
示例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()
}
示例8: displayResult
func displayResult(rows *sql.Rows) {
cols, cols_err := rows.Columns()
if cols_err != nil {
log.Fatalln(cols_err)
}
rawResult := make([][]byte, len(cols))
result := make([]string, len(cols))
dest := make([]interface{}, len(cols))
for i, _ := range cols {
dest[i] = &rawResult[i]
}
for rows.Next() {
rows.Scan(dest...)
for i, raw := range rawResult {
result[i] = string(raw)
}
for j, v := range result {
fmt.Printf("%s", v)
if j != len(result)-1 {
fmt.Printf(", ")
}
}
fmt.Printf("\n")
}
}
示例9: getCardsWithWhereQuery
// getCardsWithWhereQuery returns all of the cards that match a certain WHERE query.
func getCardsWithWhereQuery(query string, params ...interface{}) []Card {
var cards []Card
var err error
sqlQ := "select cardbody, cardtype, cardblanks, classic, id, createdon, rating, raters, approved, createdby from %s " + query
var rows *sql.Rows
if len(params) == 0 {
rows = database.GetByQuery(sqlQ)
} else {
rows = database.GetByQuery(sqlQ, params...)
}
defer rows.Close()
var card Card
for rows.Next() {
err = rows.Scan(&card.CardBody, &card.CardType,
&card.CardBlanks, &card.Classic, &card.ID,
&card.CreatedOn, &card.Rating, &card.Raters,
&card.Approved, &card.CreatedBy)
if err != nil {
log.Fatal(err)
}
cards = append(cards, card)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
return cards
}
示例10: QueryExpiredUploads
// Query all expired uploads - uploads thus not having any records which are currently active
func (tx *Transaction) QueryExpiredUploads() (result []string, err error) {
err = tx.do(func(tx *sql.Tx) (err error) {
var rows *sql.Rows
rows, err = tx.Query(`
SELECT
"u"."id" AS "id"
FROM "uploads" AS "u"
GROUP BY "u"."id"
HAVING MAX("u"."expiration") < NOW()`)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var id string
err = rows.Scan(&id)
if err != nil {
return
}
result = append(result, id)
}
return
})
return
}
示例11: QueryExpiredUpload
// Query if given upload is expired - an upload thus not having any records which are currently active
func (tx *Transaction) QueryExpiredUpload(id string) (result bool, err error) {
err = tx.do(func(tx *sql.Tx) (err error) {
var rows *sql.Rows
rows, err = tx.Query(`
SELECT
"u"."id" AS "id"
FROM "uploads" AS "u"
WHERE "u"."id" = $1
GROUP BY "u"."id"
HAVING MAX("u"."expiration") < NOW()`,
id)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
result = true
}
return
})
return
}
示例12: sqlRowsToStrings
// sqlRowsToStrings turns 'rows' into a list of rows, each of which
// is a list of column values.
// 'rows' should be closed by the caller.
// If 'format' is not nil, the values with column name
// found in the map are run through the corresponding callback.
// It returns the header row followed by all data rows.
// If both the header row and list of rows are empty, it means no row
// information was returned (eg: statement was not a query).
func sqlRowsToStrings(rows *sql.Rows, format fmtMap) ([]string, [][]string, error) {
cols, err := rows.Columns()
if err != nil {
return nil, nil, fmt.Errorf("rows.Columns() error: %s", err)
}
if len(cols) == 0 {
return nil, nil, nil
}
vals := make([]interface{}, len(cols))
for i := range vals {
vals[i] = new(interface{})
}
allRows := [][]string{}
for rows.Next() {
rowStrings := make([]string, len(cols))
if err := rows.Scan(vals...); err != nil {
return nil, nil, fmt.Errorf("scan error: %s", err)
}
for i, v := range vals {
if f, ok := format[cols[i]]; ok {
rowStrings[i] = f(*v.(*interface{}))
} else {
rowStrings[i] = formatVal(*v.(*interface{}))
}
}
allRows = append(allRows, rowStrings)
}
return cols, allRows, nil
}
示例13: sqlToMaps
func sqlToMaps(ctx *Ctx, sqlString string, sqlParams ...interface{}) (ret []map[string]interface{}, err error) {
ret = []map[string]interface{}{}
var rows *sql.Rows
rows, err = ctx.db.Query(sqlString, sqlParams...)
defer rows.Close()
if err != nil {
return
}
columns, err := rows.Columns()
if err != nil {
return
}
count := len(columns)
values := make([]interface{}, count)
valuePtrs := make([]interface{}, count)
for i := 0; i < count; i++ {
valuePtrs[i] = &values[i]
}
for rows.Next() {
retRow := map[string]interface{}{}
rows.Scan(valuePtrs...)
for i, col := range columns {
val := values[i]
switch val.(type) {
case []uint8:
retRow[col] = string(val.([]uint8))
default:
retRow[col] = val
}
}
ret = append(ret, retRow)
}
return
}
示例14: sqlToStringsMaps
func sqlToStringsMaps(ctx *Ctx, sqlString string, sqlParams ...interface{}) (ret []map[string]string, err error) {
ret = []map[string]string{}
var rows *sql.Rows
rows, err = ctx.db.Query(sqlString, sqlParams...)
defer rows.Close()
if err != nil {
return
}
columns, err := rows.Columns()
if err != nil {
return
}
count := len(columns)
values := make([]sql.NullString, count) // Без NullString невозможно определить, когда NULL
valuePtrs := make([]interface{}, count)
for i := 0; i < count; i++ {
valuePtrs[i] = &values[i]
}
for rows.Next() {
retRow := map[string]string{}
rows.Scan(valuePtrs...)
for i, col := range columns {
retRow[col] = values[i].String
}
ret = append(ret, retRow)
}
return
}
示例15: 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.")
}