func (c *Connection) Connect(tries uint) error { if tries == 0 { return nil } var err error var db *sql.DB for i := tries; i > 0; i-- { // Wait before attempt. time.Sleep(c.backoff.Wait()) // Open connection to MySQL but... db, err = sql.Open("mysql", c.dsn) if err != nil { continue } // ...try to use the connection for real. if err = db.Ping(); err != nil { // Connection failed. Wrong username or password? db.Close() continue } // Connected c.conn = db c.backoff.Success() return nil } return errors.New(fmt.Sprintf("Failed to connect to MySQL after %d tries (%s)", tries, err)) }
func Get(id string) (*Video, error) { var ( video *Video = &Video{} err error db *sql.DB ) db, err = settings.Db() if err != nil { return nil, err } defer db.Close() err = db.QueryRow("SELECT * FROM videos WHERE id = $1", id).Scan( &video.Id, &video.Title, &video.YoutubeId, &video.NicoId, &video.UploadedAt, &video.CreatedAt, &video.UpdatedAt, ) if err != nil { return nil, err } return video, nil }
func (sqlite sqlite_driver) OpenDatabase(db *sql.DB) error { if _, err := db.Exec(` CREATE TABLE IF NOT EXISTS samples ( timestamp integer, id text, channel integer, serial string, key string, min real, max real, avg real )`); err != nil { db.Close() return err } if _, err := db.Exec(` CREATE INDEX IF NOT EXISTS i_samples ON samples ( timestamp, key, id, channel, serial )`); err != nil { db.Close() return err } return nil }
func getCustomerPrice(personId int, productId int, number int) ([]*model.CustomerPrice, error) { var conn *sql.DB var stmt *sql.Stmt var err error if conn, err = db.Connect(); err != nil { return nil, err } defer conn.Close() _sql := "select * from customer_special_price where person_id = ? and product_id = ? order by create_time DESC limit ?" if stmt, err = conn.Prepare(_sql); err != nil { return nil, err } defer stmt.Close() rows, err := stmt.Query(personId, productId, number) if err != nil { return nil, err } defer rows.Close() models := []*model.CustomerPrice{} for rows.Next() { m := new(model.CustomerPrice) var blackhole sql.NullInt64 err := rows.Scan(&m.Id, &m.PersonId, &m.ProductId, &m.Price, &m.CreateTime, &blackhole /*&m.LastUsedTime */) if err != nil { panic(err) } models = append(models, m) } return models, nil }
func (s *sphinxPools) newConn() (*SphinxDB, error) { var ( err error db *sql.DB o orm.Ormer ) if db, err = sql.Open("sphinx", "root:root@tcp("+setting.SphinxHost+")/?loc=UTC"); err != nil { return nil, err } if err = db.Ping(); err != nil { db.Close() return nil, err } db.SetMaxIdleConns(1) db.SetMaxOpenConns(2) o, err = orm.NewOrmWithDB("sphinx", "sphinx", db) if err != nil { return nil, err } sdb := &SphinxDB{ alive: true, pools: s, db: db, orm: o, } return sdb, nil }
func DatabaseConnect(c conf.Database) (*sql.DB, error) { var db *sql.DB var err error if c.Type == "mysql" { if c.Password == "" { db, err = sql.Open("mysql", c.Username+"@"+c.Protocol+"("+c.Address+":"+strconv.Itoa(c.Port)+")/") } else { db, err = sql.Open("mysql", c.Username+":"+c.Password+"@"+c.Protocol+"("+c.Address+":"+strconv.Itoa(c.Port)+")/") } } if err != nil { slog.Errorf("%v: %v: %v: %v", "Database", c.Type, "connect open error", err) return nil, fmt.Errorf("%v: %v", "connect open error", err) } // check if can connect to database, if fail, check again every minute until connected for { err = db.Ping() if err == nil { break } slog.Errorf("%v: %v: %v: %v", "Database", c.Type, "connect ping error", err) next := time.After(time.Minute) select { case <-next: case <-ContinuousCollectorVars.quit: db.Close() return nil, fmt.Errorf("connect while quitting") } } return db, nil }
func process(node *types.Container, credential *types.Credential, gauge *prometheus.GaugeVec) error { var err error //logit.Info.Println("dbsize node=" + node.Name + " credentials Username:"******" Password:"******" Database:" + credential.Database + " Host:" + credential.Host) var db *sql.DB db, err = util.GetMonitoringConnection(credential.Host, credential.Username, credential.Port, credential.Database, credential.Password) defer db.Close() if err != nil { logit.Error.Println("error in getting connectionto " + credential.Host) return err } var metrics []DBMetric //logit.Info.Println("dbsize running pg2 on " + node.Name) metrics, err = pg2(db) //write metrcs to prometheus i := 0 for i = range metrics { //logit.Info.Println("dbsize setting dbsize metric") gauge.WithLabelValues(node.Name, metrics[i].Name).Set(metrics[i].Value) i++ } return nil }
func saveToDB(db *sql.DB, stockList []Stock, configuration Configuration) { db, err := sql.Open("mysql", configuration.MySQLUser+":"+configuration.MySQLPass+"@tcp("+configuration.MySQLHost+":"+configuration.MySQLPort+")/"+configuration.MySQLDB) if err != nil { fmt.Println("Could not connect to database") return } for i := range stockList { //@TODO Save results to database stock := stockList[i] // Prepare statement for inserting data insertStatement := "INSERT INTO st_data (`symbol`, `exchange`, `name`, `change`, `close`, `percentageChange`, `open`, `high`, `low`, `volume` , `avgVolume`, `high52` , `low52`, `marketCap`, `eps`, `shares`, `time`, `minute`, `hour`, `day`, `month`, `year`) " insertStatement += "VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" stmtIns, err := db.Prepare(insertStatement) if err != nil { panic(err.Error()) // proper error handling instead of panic in your app } defer stmtIns.Close() // Close the statement when we leave main() / the program terminates // Convert variables sqlChange, _ := strconv.ParseFloat(strings.Replace(stock.Change, ",", "", -1), 64) sqlClose, _ := strconv.ParseFloat(strings.Replace(stock.Close, ",", "", -1), 64) sqlPercChange, _ := strconv.ParseFloat(stock.PercentageChange, 64) sqlOpen, _ := strconv.ParseFloat(strings.Replace(stock.Open, ",", "", -1), 64) sqlHigh, _ := strconv.ParseFloat(strings.Replace(stock.High, ",", "", -1), 64) sqlLow, _ := strconv.ParseFloat(strings.Replace(stock.Low, ",", "", -1), 64) sqlHigh52, _ := strconv.ParseFloat(strings.Replace(stock.High52, ",", "", -1), 64) sqlLow52, _ := strconv.ParseFloat(strings.Replace(stock.Low52, ",", "", -1), 64) sqlEps, _ := strconv.ParseFloat(stock.EPS, 64) // Some contain letters that need to be converted sqlVolume := convertLetterToDigits(stock.Volume) sqlAvgVolume := convertLetterToDigits(stock.AverageVolume) sqlMarketCap := convertLetterToDigits(stock.MarketCap) sqlShares := convertLetterToDigits(stock.Shares) t := time.Now() utc, err := time.LoadLocation(configuration.TimeZone) if err != nil { fmt.Println("err: ", err.Error()) } sqlTime := int32(t.Unix()) sqlMinute := t.In(utc).Minute() sqlHour := t.In(utc).Hour() sqlDay := t.In(utc).Day() sqlMonth := t.In(utc).Month() sqlYear := t.In(utc).Year() _, err = stmtIns.Exec(stock.Symbol, stock.Exchange, stock.Name, sqlChange, sqlClose, sqlPercChange, sqlOpen, sqlHigh, sqlLow, sqlVolume, sqlAvgVolume, sqlHigh52, sqlLow52, sqlMarketCap, sqlEps, sqlShares, sqlTime, sqlMinute, sqlHour, sqlDay, sqlMonth, sqlYear) if err != nil { fmt.Println("Could not save results: " + err.Error()) } } defer db.Close() }
func database(res http.ResponseWriter, req *http.Request) { // fmt.Fprintln(res, "testing...\n") var db *sql.DB var err error dokku_db := os.Getenv("DATABASE_URL") db, err = sql.Open("postgres", dokku_db+"?sslmode=disable") if err != nil { fmt.Printf("sql.Open error: %v\n", err) return } defer db.Close() err = doInitialize(db) if err != nil { fmt.Print("initialize error: %v\n", err) return } err = doSelect(res, db) if err != nil { fmt.Print("select error: %v\n", err) return } }
func Disconnect(db *sql.DB) { err := db.Close() if err != nil { log.Println(err) } log.Println("Database connection: Closed.") }
func main() { // Establish mysql connection var db *sql.DB var err error db, err = sql.Open("mysql", "user:pass@tcp(127.0.0.1:3306)/db_name") if err != nil { log.Println(err) } defer db.Close() // Single query var str string str = singleQuery(db) fmt.Println(str) // Another query - multiple rows var rows *sql.Rows rows = query(db) printRows(rows) rows.Close() // Insert statement //stmt, err := db.Prepare("INSERT INTO users(username, password) VALUES(?, ?)") //if err != nil { log.Fatal(err) } //_, err = stmt.Exec("myuser", "mypass") //if err != nil { log.Fatal(err) } }
func SetEmailTaskDone(emailTask *EmailTask) bool { var db *sql.DB var stmt *sql.Stmt var err error LogError := func() { seelog.Errorf("[SetEmailTaskDone Failed] [EmailTask : %v] [ERROR : %v]", *emailTask, err) } if db, err = GetDBConnection(); err != nil { LogError() return false } defer db.Close() if stmt, err = db.Prepare("UPDATE `email_request` SET `is_done` = 1 WHERE `id` = ?"); err != nil { LogError() return false } defer stmt.Close() if _, err = stmt.Exec(emailTask.Id); err != nil { LogError() return false } return true }
// StatusUpdate called by backup jobs as they execute func StatusUpdate(w rest.ResponseWriter, r *rest.Request) { request := TaskStatus{} err := r.DecodeJsonPayload(&request) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } var dbConn *sql.DB dbConn, err = util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } defer dbConn.Close() //logit.Info.Println("StatusUpdate called") err = UpdateStatus(dbConn, &request) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } response := StatusUpdateResponse{} response.Output = "ok" w.WriteJson(&response) }
func TestEmptyDB(db *sql.DB) { q := `select relname from pg_class where relname = 'post' and relkind='r'` var initialized int = 0 rows, err := db.Query(q) if err != nil { fmt.Println("DB Query panic") panic(fmt.Sprintf("%s", err)) } for rows.Next() { var relname string err = rows.Scan(&relname) if len(relname) > 0 { initialized++ } } err = rows.Err() util.HandleErr(err) rows.Close() if initialized == 0 { q = `DROP SEQUENCE IF EXISTS post_id_seq CASCADE; DROP TABLE IF EXISTS post CASCADE; CREATE SEQUENCE post_id_seq; CREATE TABLE post(id INTEGER PRIMARY KEY NOT NULL DEFAULT nextval('post_id_seq'), title VARCHAR(32), content TEXT, user_id INTEGER, published BOOLEAN, created TIMESTAMP, modified TIMESTAMP)` _, err = db.Exec(q) util.HandleErr(err) } defer db.Close() }
func runTests(t *testing.T, dsn string, tests ...func(dbt *DBTest)) { if !available { t.Skipf("MySQL server not running on %s", netAddr) } db, err := sql.Open("mysql", dsn) if err != nil { t.Fatalf("error connecting: %s", err.Error()) } defer db.Close() db.Exec("DROP TABLE IF EXISTS test") dsn2 := dsn + "&interpolateParams=true" var db2 *sql.DB if _, err := ParseDSN(dsn2); err != errInvalidDSNUnsafeCollation { db2, err = sql.Open("mysql", dsn2) if err != nil { t.Fatalf("error connecting: %s", err.Error()) } defer db2.Close() } dbt := &DBTest{t, db} dbt2 := &DBTest{t, db2} for _, test := range tests { test(dbt) dbt.db.Exec("DROP TABLE IF EXISTS test") if db2 != nil { test(dbt2) dbt2.db.Exec("DROP TABLE IF EXISTS test") } } }
func process() { var err error var metrics []collectapi.Metric var conn *sql.DB var host = HOSTNAME var user = "******" var port = PG_PORT var database = "postgres" var password = PG_ROOT_PASSWORD conn, err = collectapi.GetMonitoringConnection(logger, host, user, port, database, password) if err != nil { logger.Println("could not connect to " + host) logger.Println(err.Error()) return } defer conn.Close() metrics, err = collectapi.GetMetrics(logger, HOSTNAME, user, PG_PORT, PG_ROOT_PASSWORD, conn) if err != nil { logger.Println("error getting metrics from " + host) logger.Println(err.Error()) return } //write metrics to Prometheus err = collectapi.WritePrometheusMetrics(logger, PROM_GATEWAY, HOSTNAME, metrics) if err != nil { logger.Println("error writing metrics from " + host) logger.Println(err.Error()) return } }
func Test_dbDevicesGet_profiles(t *testing.T) { var db *sql.DB var err error var result shared.Devices var subresult shared.Device var expected shared.Device db = createTestDb(t) defer db.Close() result, err = dbDevicesGet(db, "theprofile", true) if err != nil { t.Fatal(err) } expected = shared.Device{"type": "nic", "devicekey": "devicevalue"} subresult = result["devicename"] for key, value := range expected { if subresult[key] != value { t.Errorf("Mismatching value for key %s: %v != %v", key, subresult[key], value) } } }
func (d *PushDataBase) putConn(conn *sql.DB) { if len(d.dbpool) == d.maxConn { conn.Close() return } d.dbpool <- conn }
func Test_dbDevicesGet_containers(t *testing.T) { var db *sql.DB var err error var result shared.Devices var subresult shared.Device var expected shared.Device db = createTestDb(t) defer db.Close() result, err = dbDevicesGet(db, "thename", false) if err != nil { t.Fatal(err) } expected = shared.Device{"type": "nic", "configkey": "configvalue"} subresult = result["somename"] for key, value := range expected { if subresult[key] != value { t.Errorf("Mismatching value for key %s: %s != %s", key, subresult[key], value) } } }
func Test_deleting_an_image_cascades_on_related_tables(t *testing.T) { var db *sql.DB var err error var count int var statements string db = createTestDb(t) defer db.Close() // Drop the image we just created. statements = `DELETE FROM images;` _, err = db.Exec(statements) if err != nil { t.Errorf("Error deleting image! %s", err) } // Make sure there are 0 images_aliases entries left. statements = `SELECT count(*) FROM images_aliases;` err = db.QueryRow(statements).Scan(&count) if count != 0 { t.Errorf("Deleting an image didn't delete the image alias association! There are %d left", count) } // Make sure there are 0 images_properties entries left. statements = `SELECT count(*) FROM images_properties;` err = db.QueryRow(statements).Scan(&count) if count != 0 { t.Errorf("Deleting an image didn't delete the related images_properties! There are %d left", count) } }
func Test_dbImageGet_finds_image_for_fingerprint(t *testing.T) { var db *sql.DB var err error var result *shared.ImageBaseInfo db = createTestDb(t) defer db.Close() result, err = dbImageGet(db, "fingerprint", false, false) if err != nil { t.Fatal(err) } if result == nil { t.Fatal("No image returned!") } if result.Filename != "filename" { t.Fatal("Filename should be set.") } if result.CreationDate != 1431547174 { t.Fatal(result.CreationDate) } if result.ExpiryDate != 1431547175 { // It was short lived t.Fatal(result.ExpiryDate) } if result.UploadDate != 1431547176 { t.Fatal(result.UploadDate) } }
func Test_dbImageGet_finds_image_for_fingerprint(t *testing.T) { var db *sql.DB var err error var result *shared.ImageInfo db = createTestDb(t) defer db.Close() _, result, err = dbImageGet(db, "fingerprint", false, false) if err != nil { t.Fatal(err) } if result == nil { t.Fatal("No image returned!") } if result.Filename != "filename" { t.Fatal("Filename should be set.") } if result.CreationDate.UTC() != time.Unix(1431547174, 0).UTC() { t.Fatal(fmt.Sprintf("%s != %s", result.CreationDate, time.Unix(1431547174, 0))) } if result.ExpiryDate.UTC() != time.Unix(1431547175, 0).UTC() { // It was short lived t.Fatal(fmt.Sprintf("%s != %s", result.ExpiryDate, time.Unix(1431547175, 0))) } if result.UploadDate.UTC() != time.Unix(1431547176, 0).UTC() { t.Fatal(fmt.Sprintf("%s != %s", result.UploadDate, time.Unix(1431547176, 0))) } }
func ping(dbConn *sql.DB, port string, containerName string, containerRole string) (string, error) { var db *sql.DB var err error var userid, password, database string //get node credentials userid, password, database, err = getCredential(dbConn, containerName, containerRole) if err != nil { logit.Error.Println(err.Error()) return "down", err } db, err = util.GetMonitoringConnection(containerName, userid, port, database, password) defer db.Close() if err != nil { logit.Error.Println("error in getting connectionto " + containerName) return "down", err } var result string err = db.QueryRow("select now()::text").Scan(&result) if err != nil { logit.Error.Println("could not ping db on " + containerName) return "down", err } return "up", nil }
func cleanCloseTestDb(db *sql.DB, t *testing.T) { for _, stmt := range cleanStmts { _, err := db.Exec(stmt) checkErr(t, err) } db.Close() }
// Load a semanticizer (entity linker) from modelpath. // // Also returns a settings object that represents the dumpparser settings used // to generate the model. func Load(modelpath string) (sem *Semanticizer, settings *storage.Settings, err error) { var db *sql.DB defer func() { if db != nil && err != nil { db.Close() } }() db, settings, err = storage.LoadModel(modelpath) if err != nil { return } ngramcount, err := storage.LoadCM(db) if err != nil { return } allq, err := prepareAllQuery(db) if err != nil { return } sem = &Semanticizer{db: db, ngramcount: ngramcount, maxNGram: settings.MaxNGram, allQuery: allq} return }
func teardownAndCloseDB(t *testing.T, db *sql.DB) { err := teardownTestDB(db) if err != nil { t.Fatalf("DB teardown failed: %v", err.Error()) } db.Close() return }
func orderDrinkHandler(w http.ResponseWriter, r *http.Request) { var err error var db *sql.DB if len(r.URL.Path) <= len("/order/") { http.NotFound(w, r) return } else { // Open database db = getDBConnection() } defer db.Close() tx, _ := db.Begin() defer tx.Rollback() recipe_id := r.URL.Path[len("/order/"):] // Check drink is known var menuitem MenuItem row := tx.QueryRow("select id, name from recipe where id = ?", recipe_id) err = row.Scan(&menuitem.Id, &menuitem.DrinkName) if err == sql.ErrNoRows { http.NotFound(w, r) return } alcoholic := recipeContainsAlcohol(tx, recipe_id) // Generate order _, insertErr := tx.Exec( "insert into drink_order (create_ts, recipe_id, alcohol, id_checked, cancelled) VALUES (?, ?, ?, ?, ?)", int32(time.Now().Unix()), recipe_id, alcoholic, false, false, ) if insertErr != nil { panic(fmt.Sprintf("Insert order failed: %v", insertErr)) } var orderLogged OrderLogged // Order reference (id) row = tx.QueryRow("select max(id) from drink_order") var order_id int err = row.Scan(&order_id) orderLogged.OrderId = fmt.Sprintf(ORDER_FMT, order_id) if err == sql.ErrNoRows { http.NotFound(w, r) return } tx.Commit() t, _ := template.ParseFiles("order_logged.html") t.Execute(w, orderLogged) }
// ExecuteNow called by admin do perform an adhoc task func ExecuteNow(w rest.ResponseWriter, r *rest.Request) { request := TaskRequest{} err := r.DecodeJsonPayload(&request) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } var dbConn *sql.DB dbConn, err = util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } defer dbConn.Close() log.Println("-log- ExecuteNow.impl called profile=" + request.ProfileName) fmt.Println("-fmt- ExecuteNow.impl called profile=" + request.ProfileName) //logit.Info.Println("-logit- ExecuteNow.impl called profile=" + request.ProfileName) if request.ProfileName == "pg_basebackup" { err = ProvisionBackupJob(dbConn, &request) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } } else if request.ProfileName == "pg_backrest_restore" { logit.Info.Println("doing pg_backrest_restore job on...") err = ProvisionBackrestRestoreJob(dbConn, &request) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } } else if request.ProfileName == "restore" { logit.Info.Println("doing restore job on...") err = ProvisionRestoreJob(dbConn, &request) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } } else { err = errors.New("invalid profile name found:" + request.ProfileName) logit.Error.Println(err) rest.Error(w, err.Error(), http.StatusInternalServerError) return } logit.Info.Println("ExecuteNow.impl completed") response := ExecuteNowResponse{} response.Output = "ok" w.WriteJson(&response) }
func dbStoreImage(db *sql.DB, hash string, delHash string, orig string, thumb string) { defer db.Close() _, err := db.Exec("INSERT INTO img (hash, date, deletehash, orig, thumb) VALUES ($1, $2, $3, $4, $5);", hash, time.Now().Unix(), delHash, orig, thumb) if err != nil { fmt.Printf("Error storing image. %s", err) } }
func DailySalesData_alldata(startTime string, excludeYangYi bool) (model.ProductSales, error) { var conn *sql.DB var stmt *sql.Stmt var err error if conn, err = db.Connect(); err != nil { return nil, err } defer conn.Close() _sql := ` select DATE_FORMAT(o.create_time, '%Y-%m-%d'), sum(od.quantity) from order_detail od left join ` + "`" + `order` + "`" + ` o on od.order_track_number = o.track_number where o.type in (?,?) and o.status in (?,?,?,?) and o.create_time >= ? and od.product_id <> ? group by DATE_FORMAT(o.create_time, '%Y-%m-%d') order by DATE_FORMAT(o.create_time, '%Y-%m-%d') asc ` if stmt, err = conn.Prepare(_sql); err != nil { return nil, err } defer stmt.Close() var excluded_product_id = 0 if excludeYangYi { excluded_product_id = base.STAT_EXCLUDED_PRODUCT } rows, err := stmt.Query( model.Wholesale, model.SubOrder, // model.ShippingInstead, // 查子订单 "toprint", "todeliver", "delivering", "done", startTime, excluded_product_id, ) if db.Err(err) { return nil, err } defer rows.Close() // db.CloseRows(rows) // use db.CloseRows or rows.Close()? Is rows always nun-nil? ps := model.ProductSales{} for rows.Next() { p := new(model.SalesNode) rows.Scan(&p.Key, &p.Value) ps = append(ps, p) } return ps, nil }