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


Golang DB.Exec方法代碼示例

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


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

示例1: runExec

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

示例2: dbUpdateFromV8

func dbUpdateFromV8(db *sql.DB) error {
	stmt := `
UPDATE certificates SET fingerprint = replace(fingerprint, " ", "");
INSERT INTO schema (version, updated_at) VALUES (?, strftime("%s"));`
	_, err := db.Exec(stmt, 9)
	return err
}
開發者ID:rcj4747,項目名稱:lxd,代碼行數:7,代碼來源:db_update.go

示例3: v1CompatUpdateDatabase

func v1CompatUpdateDatabase(
	ctx *grader.Context,
	db *sql.DB,
	run *grader.RunInfo,
) {
	_, err := db.Exec(
		`UPDATE
			Runs
		SET
			status = 'ready', verdict = ?, runtime = ?, memory = ?, score = ?,
			contest_score = ?, judged_by = ?
		WHERE
			run_id = ?;`,
		run.Result.Verdict,
		run.Result.Time,
		run.Result.Memory,
		run.Result.Score,
		run.Result.ContestScore,
		run.Result.JudgedBy,
		run.ID,
	)
	if err != nil {
		ctx.Log.Error("Error updating the database", "err", err, "run", run)
	}
}
開發者ID:lhchavez,項目名稱:quark,代碼行數:25,代碼來源:v1compat_handler.go

示例4: do

func do(db *sql.DB, sql string) {
	_, err := db.Exec(sql)
	if err == nil {
		return
	}
	panic(fmt.Sprintf("Error %v running SQL: %s", err, sql))
}
開發者ID:ndarilek,項目名稱:camlistore,代碼行數:7,代碼來源:sqlite_test.go

示例5: psqlInsertHandler

// PostgreSQL INSERT Handler
func psqlInsertHandler(db *sql.DB) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		_, err := db.Exec("INSERT INTO models (uid, data) VALUES($1, $2)", "c8cb5c0b-a42e-4490-8e3d-f617f439dc27", "data")

		if err != nil {
			http.Error(w, http.StatusText(500), 500)
			return
		}

		/*
		   fmt.Println("# Deleting")
		    stmt, err = db.Prepare("delete from userinfo where uid=$1")
		    checkErr(err)

		    res, err = stmt.Exec(lastInsertId)
		    checkErr(err)

		    affect, err = res.RowsAffected()
		    checkErr(err)

		    fmt.Println(affect, "rows changed")
		*/

		w.Header().Set("Content-Type", "application/json")
		//json.NewEncoder(w).Encode(users)
	})
}
開發者ID:vvv-v13,項目名稱:backend-tools,代碼行數:29,代碼來源:psql_handlers.go

示例6: CleanAndSaveSoapItems

// supprime la vue de trollID puis sauvegarde des observations reçues par SOAP de MH, observées juste maintenant par trollId
func (store *MysqlStore) CleanAndSaveSoapItems(db *sql.DB, trollId int, items []*SoapItem) error {
	seconds := time.Now()
	sql := "delete from observation where auteur=?"
	_, err := db.Exec(sql, trollId)
	if err != nil {
		return err
	}
	sql = "insert into observation"
	sql += "        (auteur, num, date, type, nom, x, y, z)"
	sql += " values (      ?,  ?,    ?,    ?,   ?, ?, ?, ?)"
	for _, i := range items {
		var t string
		if i.Type == "TROLL" {
			t = "troll"
		} else if i.Type == "MONSTRE" {
			t = "monstre"
		} else if i.Type == "LIEU" {
			t = "lieu"
		} else if i.Type == "TRESOR" {
			t = "tresor"
		} else {
			continue
		}
		_, err = db.Exec(sql, trollId, i.Numero, seconds, t, i.Nom, i.PositionX, i.PositionY, i.PositionN)
		if err != nil {
			return err
		}
	}
	return nil
}
開發者ID:toopip,項目名稱:Chrall,代碼行數:31,代碼來源:observationstore.go

示例7: createKVTable

func createKVTable(t *testing.T, sqlDB *gosql.DB, numRows int) {
	// Fix the column families so the key counts don't change if the family
	// heuristics are updated.
	if _, err := sqlDB.Exec(`
CREATE DATABASE t;
CREATE TABLE t.kv (k INT PRIMARY KEY, v INT, FAMILY (k), FAMILY (v));
CREATE INDEX foo on t.kv (v);
`); err != nil {
		t.Fatal(err)
	}

	// Bulk insert.
	var insert bytes.Buffer
	if _, err := insert.WriteString(fmt.Sprintf(`INSERT INTO t.kv VALUES (%d, %d)`, 0, numRows-1)); err != nil {
		t.Fatal(err)
	}
	for i := 1; i < numRows; i++ {
		if _, err := insert.WriteString(fmt.Sprintf(` ,(%d, %d)`, i, numRows-i)); err != nil {
			t.Fatal(err)
		}
	}
	if _, err := sqlDB.Exec(insert.String()); err != nil {
		t.Fatal(err)
	}
}
開發者ID:BramGruneir,項目名稱:cockroach,代碼行數:25,代碼來源:drop_test.go

示例8: do

func do(db *sql.DB, sql string) {
	_, err := db.Exec(sql)
	if err == nil {
		return
	}
	log.Fatalf("Error %v running SQL: %s", err, sql)
}
開發者ID:rayleyva,項目名稱:camlistore,代碼行數:7,代碼來源:postgres_test.go

示例9: InsertPartage

// sauvegarde un nouveau partage (à l'état de proposition de a pour b)
func (store *MysqlStore) InsertPartage(db *sql.DB, trollA int, trollB int) error {
	sql := "insert ignore into"
	sql += " partage (troll_a, troll_b)"
	sql += " values (       ?,       ?)"
	_, err := db.Exec(sql, trollA, trollB)
	return err
}
開發者ID:Canop,項目名稱:Chrall,代碼行數:8,代碼來源:partagestore.go

示例10: addToMBTile

func addToMBTile(tile Tile, db *sql.DB) error {
	_, err := db.Exec("insert into tiles (zoom_level, tile_column, tile_row, tile_data) values (?, ?, ?, ?);", tile.z, tile.x, tile.flipped_y(), tile.Content)
	if err != nil {
		return err
	}
	return nil
}
開發者ID:ragsagar,項目名稱:mbtilego,代碼行數:7,代碼來源:mbutil.go

示例11: UpdateHook

func UpdateHook(db *sql.DB, query string, v *Hook) error {

	args := SliceHook(v)[1:]
	args = append(args, v.ID)
	_, err := db.Exec(query, args...)
	return err
}
開發者ID:scotthelm,項目名稱:sqlgen,代碼行數:7,代碼來源:hook_sql.go

示例12: createTestTable

// createTestTable tries to create a new table named based on the passed in id.
// It is designed to be synced with a number of concurrent calls to this
// function. Before starting, it first signals a done on the start waitgroup
// and then will block until the signal channel is closed. Once closed, it will
// proceed to try to create the table. Once the table creation is finished (be
// it successful or not) it signals a done on the end waitgroup.
func createTestTable(
	t *testing.T,
	tc *testcluster.TestCluster,
	id int,
	db *gosql.DB,
	wgStart *sync.WaitGroup,
	wgEnd *sync.WaitGroup,
	signal chan struct{},
	completed chan int,
) {
	defer wgEnd.Done()

	wgStart.Done()
	<-signal

	tableSQL := fmt.Sprintf(`
		CREATE TABLE IF NOT EXISTS "test"."table_%d" (
			id INT PRIMARY KEY,
			val INT
		)`, id)

	for {
		if _, err := db.Exec(tableSQL); err != nil {
			if testutils.IsSQLRetryableError(err) {
				continue
			}
			t.Errorf("table %d: could not be created: %v", id, err)
			return
		}
		completed <- id
		break
	}
}
開發者ID:knz,項目名稱:cockroach,代碼行數:39,代碼來源:create_test.go

示例13: addChannelHistory

func addChannelHistory(s *slack.Slack, db *sql.DB, channel, oldest string) (string, error) {
	params := slack.NewHistoryParameters()
	params.Oldest = oldest
	params.Count = 1000
	history, err := s.GetChannelHistory(channel, params)
	if err != nil {
		return "", err
	}
	for _, msg := range history.Messages {
		if msg.SubType != "" {
			continue
		}
		fmt.Printf("%s: %s\n", msg.User, msg.Text)
		ts := timestampToTime(msg.Timestamp)
		_, err := db.Exec(
			`INSERT INTO messages(channel_id, user_id, text, timestamp, created_at, updated_at)
			 VALUES(?, ?, ?, ?, NOW(), NOW())
			`,
			channel, msg.User, msg.Text, ts.Format("2006-01-02 15:04:05"))
		if err != nil {
			return "", err
		}
	}

	if len(history.Messages) > 0 {
		return history.Messages[0].Timestamp, nil
	}

	return "", nil
}
開發者ID:kan,項目名稱:slack-door,代碼行數:30,代碼來源:crawler.go

示例14: prepareDatabase

func prepareDatabase(db *sql.DB) error {
	_, err := db.Exec(fmt.Sprintf("CREATE TABLE IF NOT EXISTS %v (id text not null, applied_at timestamp not null)", tableName))
	if err != nil {
		return err
	}
	return nil
}
開發者ID:umsatz,項目名稱:api,代碼行數:7,代碼來源:migrate.go

示例15: insertTask

func insertTask(db *sql.DB, serializer format.Serializer, task *models.Task, malformedTaskDefinition bool) {
	taskDefData, err := serializer.Marshal(logger, format.ENCRYPTED_PROTO, task.TaskDefinition)
	Expect(err).NotTo(HaveOccurred())

	if malformedTaskDefinition {
		taskDefData = []byte("{{{{{{{{{{")
	}

	queryStr := `INSERT INTO tasks
						  (guid, domain, created_at, updated_at, first_completed_at, state,
							cell_id, result, failed, failure_reason, task_definition)
					    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
	if test_helpers.UsePostgres() {
		queryStr = test_helpers.ReplaceQuestionMarks(queryStr)
	}
	result, err := db.Exec(
		queryStr,
		task.TaskGuid,
		task.Domain,
		task.CreatedAt,
		task.UpdatedAt,
		task.FirstCompletedAt,
		task.State,
		task.CellId,
		task.Result,
		task.Failed,
		task.FailureReason,
		taskDefData,
	)
	Expect(err).NotTo(HaveOccurred())
	Expect(result.RowsAffected()).NotTo(Equal(1))
}
開發者ID:cloudfoundry,項目名稱:bbs,代碼行數:32,代碼來源:task_db_test.go


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