當前位置: 首頁>>代碼示例>>Golang>>正文


Golang DB.Query方法代碼示例

本文整理匯總了Golang中database/sql.DB.Query方法的典型用法代碼示例。如果您正苦於以下問題:Golang DB.Query方法的具體用法?Golang DB.Query怎麽用?Golang DB.Query使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在database/sql.DB的用法示例。


在下文中一共展示了DB.Query方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: ObservationsAutour

func (store *MysqlStore) ObservationsAutour(db *sql.DB, x int, y int, z int, dist int, trollId int, amis []int, withTresors bool) ([]*Observation, error) {
	sql := "select auteur, num, date, type, nom, x, y, z from observation where"
	sql += " x>" + strconv.Itoa(x-dist-1) + " and x<" + strconv.Itoa(x+dist+1)
	sql += " and y>" + strconv.Itoa(y-dist-1) + " and y<" + strconv.Itoa(y+dist+1)
	sql += " and z>" + strconv.Itoa(z-dist/2-1) + " and z<" + strconv.Itoa(z+dist/2+1)
	if !withTresors {
		sql += " and type<>'tresor'"
	}
	sql += " and auteur in (" + strconv.Itoa(trollId)
	for _, id := range amis {
		sql += "," + strconv.Itoa(id)
	}
	sql += ") order by type, num, date desc"
	rows, err := db.Query(sql)
	observations := make([]*Observation, 0, 20)
	for rows.Next() {
		r := new(Observation)
		err = rows.Scan(&r.Auteur, &r.Num, &r.Date, &r.Type, &r.Nom, &r.X, &r.Y, &r.Z)
		if err != nil {
			return nil, err
		}
		if len(observations) > 0 && r.Num == observations[len(observations)-1].Num { // dédoublonnage
			continue
		}
		observations = append(observations, r)

	}
	rows.Close()
	return observations, nil
}
開發者ID:toopip,項目名稱:Chrall,代碼行數:30,代碼來源:observationstore.go

示例2: getApplicationDeployments

func getApplicationDeployments(db *sql.DB, a *models.Application, limit int) ([]*models.Deployment, error) {
	deployments := []*models.Deployment{}

	rows, err := db.Query(applicationDeploymentsStmt, a.Name, limit)
	if err != nil {
		return deployments, err
	}
	defer rows.Close()

	for rows.Next() {
		var state string
		d := &models.Deployment{}

		err = rows.Scan(&d.Id, &d.UserId, &d.TargetName, &d.CommitSha, &d.Branch, &d.Comment, &state, &d.CreatedAt)
		if err != nil {
			return deployments, err
		}

		d.State = models.DeploymentState(state)

		deployments = append(deployments, d)
	}

	if err := rows.Err(); err != nil {
		return deployments, err
	}

	return deployments, nil
}
開發者ID:MahaKoala,項目名稱:applikatoni,代碼行數:29,代碼來源:database.go

示例3: GetHistoryPlayers

func GetHistoryPlayers(db *sql.DB, days int) ([]HistoryPlayers, error) {
	var data []HistoryPlayers
	var query string
	switch days {
	case 1:
		query = "SELECT history_slots_used, history_date FROM history WHERE history_date > NOW() - INTERVAL 1 DAY"
	case 7:
		query = "SELECT a.history_slots_used, a.history_date FROM (SELECT history_slots_used, history_date, DATE_FORMAT(history_date, '%p%d%m%y') AS g FROM history WHERE history_date > NOW() - INTERVAL 1 WEEK GROUP BY g) AS a"
	case 30:
		query = "SELECT a.history_slots_used, a.history_date FROM (SELECT history_slots_used, history_date, DATE_FORMAT(history_date, '%d%m%y') AS g FROM history WHERE history_date > NOW() - INTERVAL 1 MONTH GROUP BY g) AS a"
	case 365:
		query = "SELECT a.history_slots_used, a.history_date FROM (SELECT history_slots_used, history_date, DATE_FORMAT(history_date, '%u%y') AS g FROM history WHERE history_date > NOW() - INTERVAL 1 YEAR GROUP BY g) AS a"
	}
	rows, err := db.Query(query)
	if err != nil {
		return data, err
	}
	defer rows.Close()
	for rows.Next() {
		var tmp HistoryPlayers
		if err := rows.Scan(&tmp.Total, &tmp.Date); err != nil {
			return data, err
		}
		data = append(data, tmp)
	}
	return data, nil
}
開發者ID:quickdevel,項目名稱:statsamp,代碼行數:27,代碼來源:server.go

示例4: DeployCumulative

func DeployCumulative(db *sql.DB, simid []byte, proto string) (xys []XY, err error) {
	sql := `SELECT Time, IFNULL(Count, 0) FROM 
			TimeList LEFT JOIN
			(SELECT ti.Time AS Timestep,COUNT(*) AS Count FROM
				TimeList AS ti 
				JOIN Agents AS ag ON (ti.Time >= ag.EnterTime) AND (ag.ExitTime >= ti.Time OR ag.ExitTime IS NULL)
				WHERE
				    ti.SimId = ag.SimId
					AND ag.SimId = ?
					AND ag.Prototype = ?
				GROUP BY ti.Time
				ORDER BY ti.Time) AS foo ON foo.Timestep = TimeList.Time;`
	rows, err := db.Query(sql, simid, proto)
	if err != nil {
		return nil, err
	}

	for rows.Next() {
		xy := XY{}
		if err := rows.Scan(&xy.X, &xy.Y); err != nil {
			return nil, err
		}
		xys = append(xys, xy)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return xys, nil
}
開發者ID:katyhuff,項目名稱:cyan,代碼行數:29,代碼來源:query.go

示例5: TableList

func TableList(db *sql.DB) (map[string]Table, error) {
	rows, err := db.Query("SELECT id, rev, doc FROM divan WHERE doc->>'type' = 'table'")
	if err != nil && err.Error() == `pq: relation "divan" does not exist` {
		return nil, fmt.Errorf("divan table missing! Trying running with -b flag to bootstrap the environment or create the table manually.")
	}
	if err != nil {
		return nil, err
	}

	tables := make(map[string]Table)
	for rows.Next() {
		doc := new(Doc)
		if err := rows.Scan(&doc.Id, &doc.Rev, &doc.Doc); err != nil {
			return nil, err
		}
		t := new(Table)
		t.Db = db
		err := doc.JSON(t)
		if err != nil {
			return nil, err
		}
		tables[t.Name] = *t
	}

	return tables, nil
}
開發者ID:lancecarlson,項目名稱:divan,代碼行數:26,代碼來源:table.go

示例6: getDeploymentLogEntries

func getDeploymentLogEntries(db *sql.DB, d *models.Deployment) ([]*deploy.LogEntry, error) {
	entries := []*deploy.LogEntry{}

	rows, err := db.Query(deploymentLogEntriesStmt, d.Id)
	if err != nil {
		return entries, err
	}
	defer rows.Close()

	for rows.Next() {
		var entryType string
		e := &deploy.LogEntry{}

		err = rows.Scan(&e.Id, &e.DeploymentId, &entryType, &e.Origin, &e.Message, &e.Timestamp)
		if err != nil {
			return entries, err
		}

		e.EntryType = deploy.LogEntryType(entryType)

		entries = append(entries, e)
	}

	if err := rows.Err(); err != nil {
		return entries, err
	}

	return entries, nil
}
開發者ID:MahaKoala,項目名稱:applikatoni,代碼行數:29,代碼來源:database.go

示例7: runQuery

func runQuery(ctx context.Context, db *sql.DB, query string) (*sql.Rows, error) {
	done := make(chan struct{})
	var (
		rows   *sql.Rows
		errMsg error
	)
	go func() {
		for {
			rs, err := db.Query(query)
			if err != nil {
				errMsg = err
				time.Sleep(time.Second)
				continue
			} else {
				rows = rs
				errMsg = nil
				done <- struct{}{}
				break
			}
		}
	}()
	select {
	case <-done:
		return rows, errMsg
	case <-ctx.Done():
		return nil, fmt.Errorf("runQuery %s timed out with %v / %v", query, ctx.Err(), errMsg)
	}
}
開發者ID:xqbumu,項目名稱:learn,代碼行數:28,代碼來源:database.go

示例8: DataCheck

func DataCheck(qry string, conn *sql.DB) bool {
	// conn, err := connect.GetJanusCon()
	// if err != nil {
	// 	panic(err)
	// }
	// defer conn.Close()

	rowscheck, err := conn.Query(qry)
	if err != nil {
		log.Printf(`Error with "%s": %s`, qry, err)
	}
	len := 0
	for rowscheck.Next() {
		len = len + 1
	}

	// conn.Close()

	if len > 0 {
		return true
	} else {
		return false
	}

}
開發者ID:OpenCoreData,項目名稱:ocdJanus,代碼行數:25,代碼來源:dataCheck.go

示例9: SelectBodys

func SelectBodys(db *sql.DB, ids []int) (map[int]string, error) {
	m := map[int]string{}
	strs := make([]string, len(ids))
	for i, id := range ids {
		strs[i] = fmt.Sprintf("%d", id)
	}
	clause := strings.Join(strs, ",")
	rows, err := db.Query(
		fmt.Sprintf(
			"SELECT id, body FROM reviews WHERE id IN (%s)",
			clause,
		),
	)
	if err != nil {
		return m, err
	}
	for rows.Next() {
		var id int
		var body string
		if err := rows.Scan(&id, &body); err != nil {
			return m, fmt.Errorf("SELECT error: %s", err)
		}
		m[id] = body
	}
	return m, nil
}
開發者ID:ericrose,項目名稱:pitchdex,代碼行數:26,代碼來源:database.go

示例10: altSet

// postgres does not have REPLACE INTO (upsert), so we use that custom
// one for Set operations instead
func altSet(db *sql.DB, key, value string) error {
	r, err := db.Query("SELECT replaceinto($1, $2)", key, value)
	if err != nil {
		return err
	}
	return r.Close()
}
開發者ID:t3rm1n4l,項目名稱:camlistore,代碼行數:9,代碼來源:postgresindexer.go

示例11: getSummary

func getSummary(db *sql.DB) (summary, error) {
	s := newSummary()

	rows, err := db.Query(`SELECT Day, Version, Count FROM VersionSummary WHERE Day > now() - '1 year'::INTERVAL;`)
	if err != nil {
		return summary{}, err
	}
	defer rows.Close()

	for rows.Next() {
		var day time.Time
		var ver string
		var num int
		err := rows.Scan(&day, &ver, &num)
		if err != nil {
			return summary{}, err
		}

		if ver == "v0.0" {
			// ?
			continue
		}

		// SUPER UGLY HACK to avoid having to do sorting properly
		if len(ver) == 4 { // v0.x
			ver = ver[:3] + "0" + ver[3:] // now v0.0x
		}

		s.setCount(day.Format("2006-01-02"), ver, num)
	}

	return s, nil
}
開發者ID:modulexcite,項目名稱:usage-reporting,代碼行數:33,代碼來源:main.go

示例12: gatherPerfEventWaits

// gatherPerfEventWaits can be used to get total time and number of event waits
func (m *Mysql) gatherPerfEventWaits(db *sql.DB, serv string, acc telegraf.Accumulator) error {
	rows, err := db.Query(perfEventWaitsQuery)
	if err != nil {
		return err
	}
	defer rows.Close()

	var (
		event               string
		starCount, timeWait float64
	)

	servtag, err := parseDSN(serv)
	if err != nil {
		servtag = "localhost"
	}
	tags := map[string]string{
		"server": servtag,
	}
	for rows.Next() {
		if err := rows.Scan(&event, &starCount, &timeWait); err != nil {
			return err
		}
		tags["event_name"] = event
		fields := map[string]interface{}{
			"events_waits_total":         starCount,
			"events_waits_seconds_total": timeWait / picoSeconds,
		}

		acc.AddFields("mysql_perf_schema", fields, tags)
	}
	return nil
}
開發者ID:li-ang,項目名稱:telegraf,代碼行數:34,代碼來源:mysql.go

示例13: gatherInfoSchemaAutoIncStatuses

// gatherInfoSchemaAutoIncStatuses can be used to get auto incremented values of the column
func (m *Mysql) gatherInfoSchemaAutoIncStatuses(db *sql.DB, serv string, acc telegraf.Accumulator) error {
	rows, err := db.Query(infoSchemaAutoIncQuery)
	if err != nil {
		return err
	}
	defer rows.Close()

	var (
		schema, table, column string
		incValue, maxInt      uint64
	)

	servtag, err := parseDSN(serv)
	if err != nil {
		servtag = "localhost"
	}

	for rows.Next() {
		if err := rows.Scan(&schema, &table, &column, &incValue, &maxInt); err != nil {
			return err
		}
		tags := map[string]string{
			"server": servtag,
			"schema": schema,
			"table":  table,
			"column": column,
		}
		fields := make(map[string]interface{})
		fields["auto_increment_column"] = incValue
		fields["auto_increment_column_max"] = maxInt

		acc.AddFields("mysql_info_schema", fields, tags)
	}
	return nil
}
開發者ID:li-ang,項目名稱:telegraf,代碼行數:36,代碼來源:mysql.go

示例14: ScrapeEngineTokudbStatus

// ScrapeEngineTokudbStatus scrapes from `SHOW ENGINE TOKUDB STATUS`.
func ScrapeEngineTokudbStatus(db *sql.DB, ch chan<- prometheus.Metric) error {
	tokudbRows, err := db.Query(engineTokudbStatusQuery)
	if err != nil {
		return err
	}
	defer tokudbRows.Close()

	var temp, key string
	var val sql.RawBytes

	for tokudbRows.Next() {
		if err := tokudbRows.Scan(&temp, &key, &val); err != nil {
			return err
		}
		key = strings.ToLower(key)
		if floatVal, ok := parseStatus(val); ok {
			ch <- prometheus.MustNewConstMetric(
				newDesc(tokudb, sanitizeTokudbMetric(key), "Generic metric from SHOW ENGINE TOKUDB STATUS."),
				prometheus.UntypedValue,
				floatVal,
			)
		}
	}
	return nil
}
開發者ID:yanghongkjxy,項目名稱:mysqld_exporter,代碼行數:26,代碼來源:engine_tokudb.go

示例15: LockPartition

func LockPartition(pg *sql.DB, ns string, max uint64) (uint64, error) {
	tab := crc32.MakeTable(crc32.IEEE)
	for {
		var p uint64
		for p = 0; p < max; p++ {
			pId := fmt.Sprintf("%s.%d", ns, p)
			check := crc32.Checksum([]byte(pId), tab)
			rows, err := pg.Query("select pg_try_advisory_lock($1)", check)
			if err != nil {
				continue
			}
			for rows.Next() {
				var result sql.NullBool
				rows.Scan(&result)
				if result.Valid && result.Bool {
					fmt.Printf("at=%q partition=%d max=%d\n",
						"acquired-lock", p, max)
					rows.Close()
					return p, nil
				}
			}
			rows.Close()
		}
		fmt.Printf("at=%q\n", "waiting-for-partition-lock")
		time.Sleep(time.Second * 10)
	}
	return 0, errors.New("Unable to lock partition.")
}
開發者ID:ericfode,項目名稱:l2met,代碼行數:28,代碼來源:utils.go


注:本文中的database/sql.DB.Query方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。