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

Golang sqlx.Open函数代码示例

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

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



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

示例1: createNewDB

// TODO (ajafri): we perform a file read on each one of these calls so use it sparingly or change the pattern
func createNewDB() (*sqlx.DB, error) {
	var version string = "dbVersion"

	b, err := ioutil.ReadFile("bridgdDBVersion.txt")
	if err != nil {
		b = []byte("") // simulate a version mismatch if reading the file throws an error
	}

	version = string(b)
	_, err = os.Stat(dbFile)

	if version != dbVersion || os.IsNotExist(err) {
		log.Println("Version difference detected - recreating database")

		os.Remove(dbFile) // clear the db if it is not versioned to the current version

		// let's create a new db and instantiate the structure
		db, err := sqlx.Open("sqlite3", "./rooms.db")
		if err != nil {
			return db, err
		}

		/* TABLE CREATION */
		_, err = db.Exec(schema)
		if err != nil {
			log.Printf("%q: %s\n", err, schema)
			return db, err
		}

		room := Room{Id: 1, Name: "no-yolo-zone"}
		// TODO (ajafri): testing code to initialize table with data. Take out.
		_, err = db.NamedExec("insert into rooms(id, name) values(:id, :name)", room)
		if err != nil {
			log.Printf("%q: %s\n", err)
			return db, err
		}

		// TODO (ajafri): testing code to initialize table with data. Take out.
		song := Song{VideoData: "{ \"id\": { \"kind\": \"youtube#video\", \"videoId\": \"IDKMKBmpwrg\" }, \"snippet\": { \"title\": \"Tinashe - Player (Audio) ft. Chris Brown\", \"description\": \"\\\"Player\\\" feat. Chris Brown from Tinashe's forthcoming new album, Joyride. Apple Music: http://smarturl.it/PlayerCBa?IQid=yt Spotify: http://smarturl.it/PlayerCBs?\", \"thumbnails\": { \"default\": { \"url\": \"https://i.ytimg.com/vi/IDKMKBmpwrg/default.jpg\" } }, \"channelTitle\": \"TinasheOfficialVEVO\" } }"}

		_, err = db.NamedExec("insert into songs(songId, roomId, videoData) values(:songId, :id, :videoData)", map[string]interface{}{"songId": "IDKMKBmpwrg", "id": room.Id, "videoData": song.VideoData})
		if err != nil {
			log.Printf("%q: %s\n", err)
			return db, err
		}

		err = ioutil.WriteFile("bridgdDBVersion.txt", []byte(dbVersion), 0644)
		if err != nil {
			return db, err
		}
	}

	return sqlx.Open("sqlite3", "./rooms.db")
}
开发者ID:ahmedjafri,项目名称:Bridgd-golang,代码行数:55,代码来源:marshaller.go


示例2: Open

func Open(url string) (db *sqlx.DB, err error) {
	switch {
	case strings.HasPrefix(url, "mysql://"):
		db, err = sqlx.Open(`mysql`, url[len("mysql://"):])
	case strings.HasPrefix(url, "postgres://"):
		db, err = sqlx.Open(`postgres`, url)
	case strings.HasPrefix(url, "mssql://"):
		db, err = sqlx.Open("mssql", splitMssql(url))
	default:
		db, err = nil, ErrProtocol
	}
	return db, err
}
开发者ID:in3pid,项目名称:dbx,代码行数:13,代码来源:dbx.go


示例3: setupDB

func setupDB() error {
	var err error

	dbDir = filepath.Join(dataDir, "db")
	dbFile = filepath.Join(dbDir, "db.sql")
	err = os.MkdirAll(dbDir, 0700)
	if err != nil {
		return err
	}

	db, err = sqlx.Open("sqlite3", dbFile)
	if err != nil {
		return err
	}

	_, err = db.Exec(messagesSchema)
	if err != nil {
		return err
	}

	_, err = db.Exec(sessionsSchema)
	if err != nil {
		return err
	}

	_, err = db.Exec(groupsSchema)
	if err != nil {
		return err
	}

	migrations()

	return loadMessagesFromDB()
}
开发者ID:janimo,项目名称:textsecure-qml,代码行数:34,代码来源:db.go


示例4: waitingForStartup

func waitingForStartup(ipAddress string) (string, error) {

	connect, err := sqlx.Open("postgres", fmt.Sprintf("postgres://postgres:[email protected]%s/postgres?sslmode=disable", ipAddress))

	if err != nil {

		return "", err
	}

	defer connect.Close()

	var serverVersion string

	for i := 0; i < 30; i++ {

		time.Sleep(time.Second * 2)

		if err := connect.Get(&serverVersion, "SHOW server_version"); err == nil {

			return serverVersion, nil
		}
	}

	return "", fmt.Errorf("connect timeout: %s", ipAddress)
}
开发者ID:postgres-ci,项目名称:worker,代码行数:25,代码来源:plpgsql.go


示例5: NewDB

// NewDB constructor for database connection.
func NewDB(driver, info string) (*DB, error) {
	db, err := sqlx.Open(driver, info)
	if err != nil {
		return &DB{}, err
	}
	return &DB{db}, nil
}
开发者ID:manifest-destiny,项目名称:api,代码行数:8,代码来源:db.go


示例6: main

func main() {
	db, err := sqlx.Open("postgres", "postgres://postgres:[email protected]/godos_development?sslmode=disable")
	if err != nil {
		log.Fatal(err)
	}

	tx := db.MustBegin()
	now := time.Now()
	t := Todo{
		Subject:     "Mow Lawn!",
		Description: "Yuck!",
		CreatedAt:   now,
		UpdatedAt:   now,
	}
	tx.Exec("INSERT INTO todos (subject, description, created_at, updated_at) VALUES ($1, $2, $3, $4)", t.Subject, t.Description, t.CreatedAt, t.UpdatedAt)
	// // demonstrate the transaction:
	// tx.Exec("INSERT INTO todos (subject, description, created_at, updated_at) VALUES ($1, $2, $3, $4)", t.Subject, t.Description, t.CreatedAt, t.UpdatedAt)
	// tx.Exec("INSERT INTO todos (subject, description, created_at, updated_at) VALUES ($1, $2, $3, $4)", nil, t.Description, t.CreatedAt, t.UpdatedAt)
	tx.Commit()

	todos := []Todo{}
	db.Select(&todos, "select * from todos")

	for _, todo := range todos {
		log.Printf("Subject is %s", todo.Subject)
	}
}
开发者ID:SiroDiaz,项目名称:csuf,代码行数:27,代码来源:6.go


示例7: GetLeague

func GetLeague() ([]modal.Modal, error) {
	var db *sqlx.DB
	var err error
	var leagues []modal.Modal

	if db, err = sqlx.Open("mysql", user+":"+password+"@/Dota?parseTime=true"); err != nil {
		return leagues, err
	}
	defer db.Close()

	// find league where deleted is 0000-00-00 00:00:00
	rows, err := db.Queryx("select * from League where deleted = ?", deletedTime)
	if err != nil {
		return leagues, err
	}

	for rows.Next() {
		var league modal.League

		err = rows.StructScan(&league)
		if err != nil {
			return leagues, err
		}

		leagues = append(leagues, league)
	}
	return leagues, nil
}
开发者ID:bealox,项目名称:dotago,代码行数:28,代码来源:repoleague.go


示例8: GetTeam

func GetTeam() ([]modal.Modal, error) {
	var db *sqlx.DB
	var err error
	var teams []modal.Modal

	if db, err = sqlx.Open("mysql", user+":"+password+"@/Dota?parseTime=true"); err != nil {
		return teams, err
	}
	defer db.Close()

	rows, err := db.Queryx("select * from Team")
	if err != nil {
		return teams, err
	}

	for rows.Next() {
		var team modal.Team

		err = rows.StructScan(&team)
		if err != nil {
			return teams, err
		}

		teams = append(teams, team)
	}
	return teams, nil
}
开发者ID:bealox,项目名称:dotago,代码行数:27,代码来源:repoteam.go


示例9: dbconnect

func dbconnect() {
	// Connect to database
	var err error
	db, err = sqlx.Open("sqlite3", *database)
	if err != nil {
		log.Fatal("Error connecting to database: %s\n", err)
	}

	// Ping the database
	err = db.Ping()
	if err != nil {
		log.Fatal("Error pinging database: %s\n", err)
	}

	// Setup migrations
	migrations := &migrate.FileMigrationSource{
		Dir: "app/database/migrations",
	}

	// Run migrations
	n, err := migrate.Exec(db.DB, "sqlite3", migrations, migrate.Up)
	if err != nil {
		log.Fatal("Error running database migrations: %s\n", err)
	} else {
		if n == 0 {
			log.Println("Nothing to migrate")
		} else {
			log.Println("Applied %d migrations", n)
		}
	}
}
开发者ID:lukevers,项目名称:converse,代码行数:31,代码来源:database.go


示例10: SetUpSuite

func (s *testDriverSuite) SetUpSuite(c *C) {
	dsn := fmt.Sprintf("[email protected]%s:3306?test", *testHost)

	var err error
	s.db, err = sqlx.Open("mysql", dsn)
	c.Assert(err, IsNil)
}
开发者ID:xurenlu,项目名称:go-mysql,代码行数:7,代码来源:dirver_test.go


示例11: main

func main() {
	log.Println("Main")
	db, _ = sqlx.Open("postgres", "dbname=terry host=localhost user=terry sslmode=disable")
	log.Println(db)

	now := time.Now()

	//numberOfWorker := 1
	//w := Writer{100000, db}
	//w.Run()

	numberOfWorker := 3
	var wg sync.WaitGroup
	wg.Add(numberOfWorker)
	for i := 0; i < numberOfWorker; i++ {
		go func(i int, conn *sqlx.DB, wg *sync.WaitGroup) {
			w := Writer{100000, conn}
			w.Run()
			log.Println("Writer", i, "finished")
			wg.Done()
		}(i, db, &wg)

	}

	wg.Wait()

	log.Println(numberOfWorker, "Writer", "took", time.Now().Sub(now))

}
开发者ID:terryh,项目名称:wbench,代码行数:29,代码来源:main.go


示例12: buildSchema

func (p *mysqlSchema) buildSchema() error {
	var err error
	p.db, err = sqlx.Open("mysql", p.URL)
	if err != nil {
		return err
	}
	defer p.db.Close()

	res, err := p.db.Queryx(fmt.Sprintf("select TABLE_NAME as name from information_schema.TABLES where TABLE_SCHEMA = '%s'", p.Name))
	if err != nil {
		return err
	}
	for res.Next() {
		table := &fizz.Table{
			Columns: []fizz.Column{},
			Indexes: []fizz.Index{},
		}
		err = res.StructScan(table)
		if err != nil {
			return err
		}
		err = p.buildTableData(table)
		if err != nil {
			return err
		}

	}
	return nil
}
开发者ID:markbates,项目名称:pop,代码行数:29,代码来源:mysql_meta.go


示例13: GetAbility

func GetAbility() ([]modal.Modal, error) {
	var db *sqlx.DB
	var err error
	var abilities []modal.Modal

	if db, err = sqlx.Open("mysql", user+":"+password+"@/Dota?parseTime=true"); err != nil {
		return abilities, err
	}
	defer db.Close()

	rows, err := db.Queryx("select * from Ability")
	if err != nil {
		return abilities, err
	}

	for rows.Next() {
		var ability modal.Ability

		err = rows.StructScan(&ability)
		if err != nil {
			return abilities, err
		}

		abilities = append(abilities, ability)
	}
	return abilities, nil
}
开发者ID:bealox,项目名称:dotago,代码行数:27,代码来源:repoability.go


示例14: TestQueryVariable

func TestQueryVariable(t *testing.T) {

	db, err := sqlx.Open("sqlite3", "./test_db.db")
	if err != nil {
		t.Fatal(err)
	}

	const q = `{
  Products(ProductID: 3) {
    ProductName,
    UnitsInStock,
    CategoryId,
    Categories(CategoryID: $CategoryID) {
       CategoryName
    }
  }
}`
	if ast, err := parse.NewQuery([]byte(q)); err != nil {
		t.Error(err.Error())
	} else {
		//		log.Println(prettyprint.AsJSON(d(ast, db, t)))
		d(ast, db, t)
	}

	defer db.Close()

}
开发者ID:sevki,项目名称:g2sd,代码行数:27,代码来源:sql_test.go


示例15: TestQueryComplex

func TestQueryComplex(t *testing.T) {

	db, err := sqlx.Open("sqlite3", "./test_db.db")
	if err != nil {
		t.Fatal(err)
	}

	const q = `{
  Products(ProductID: 9) {
    ProductName,
    UnitsInStock,
    ProductID,
    OrderDetails(ProductID: $ProductID) {
       OrderID,
       Orders(OrderID: $OrderID) {
         EmployeeID,
         Employees(EmployeeID: $EmployeeID) {
            FirstName
         }
       }
    }
  }
}`
	if ast, err := parse.NewQuery([]byte(q)); err != nil {
		t.Error(err.Error())
	} else {
		log.Println(prettyprint.AsJSON(d(ast, db, t)))
		//d(ast, db, t)
	}

	defer db.Close()

}
开发者ID:sevki,项目名称:g2sd,代码行数:33,代码来源:sql_test.go


示例16: main

func main() {
	DB, Err := sqlx.Open(db_driver, db_source)
	CheckErr(Err)
	if DB.Ping() != nil {
		fmt.Println("Cannot connect to Database")
	} else {
		fmt.Println("Connected to database")
	}

	//menyalakan web server
	r := gin.Default()

	r.Use(AddDB(DB))

	//load template

	r.LoadHTMLGlob("./template/*")
	r.GET("/testinput", func(c *gin.Context) {
		c.HTML(http.StatusOK, "testinput.tmpl", gin.H{})
	})

	r.POST("/coba", regisDevice)

	r.GET("/out", outDevice)

	//tx.MustExec("INSERT INTO device_list (device_name, host, port, token, description) VALUES ($1, $2, $3, $4, $5)", "arduino", "29", "33", "3", "tes masuk")

	r.Run(":8080") // listen and serve on 0.0.0.0:8080

}
开发者ID:freycool,项目名称:tesnunuardi,代码行数:30,代码来源:test.go


示例17: OpenDB

// OpenDB opens the database in the given directory; if required, the database
// will be initialized.
func OpenDB(dir string) (err error) {
	log.SetLevelByString("error")

	dir = filepath.Join(dir, "tidb")
	_, err = os.Stat(dir)
	init := os.IsNotExist(err)

	name := "tidb"
	db, err = sqlx.Open("tidb", "goleveldb://"+dir+"/"+name)
	if err != nil {
		return fmt.Errorf("db open failed: %s", err)
	}
	if err := db.Ping(); err != nil {
		return fmt.Errorf("db ping failed: %s", err)
	}

	if init {
		// b, err := ioutil.ReadFile(filepath.Join("data", "schema.sql"))
		// if err != nil {
		// return fmt.Errorf("read schema file failed: %s", err)
		// }
		// if _, err = db.Exec(string(b)); err != nil {
		if _, err = db.Exec(schemasql); err != nil {
			return fmt.Errorf("exec schema failed: %s", err)
		}
		if err = insertCards(); err != nil {
			return fmt.Errorf("insert cards failed: %s", err)
		}
	}

	return nil
}
开发者ID:stepheninabox,项目名称:fowtcg,代码行数:34,代码来源:tidb.go


示例18: main

func main() {

	var err error

	loadConfig()

	//conenct to api databases
	db, err = sqlx.Open("postgres", cfg.DB.connString+" sslmode=disable")
	if err != nil {
		log.Println("error while connecting to database:", err)
		panic(err)
	}

	db.SetMaxIdleConns(cfg.PoolMin)
	db.SetMaxOpenConns(cfg.PoolMax)

	r := mux.NewRouter()
	r.HandleFunc("/query", query).Methods("POST")

	// start HTTP server
	fmt.Println("starting server on port:", cfg.Port)
	if err := http.ListenAndServe(fmt.Sprintf("localhost:%d", cfg.Port), r); err != nil {
		log.Fatal("error while starting http server:", err)
	}
}
开发者ID:Jarema,项目名称:db-connection-pooling-daemon,代码行数:25,代码来源:main.go


示例19: Start

func (s *Server) Start() {
	config := osin.NewServerConfig()
	config.ErrorStatusCode = 401

	url := fmt.Sprintf("postgres://%s:%[email protected]%s/%s?sslmode=disable",
		os.Getenv("DB_USER"),
		os.Getenv("DB_PASS"),
		os.Getenv("DB_HOST"),
		os.Getenv("DB_NAME"),
	)

	db, err := sqlx.Open("postgres", url)
	if err != nil {
		log.Fatalln(err.Error())
	}

	storage := postgres.New(db.DB)
	s.server = osin.NewServer(config, storage)

	wsContainer := restful.NewContainer()

	r := UserResource{}
	r.Register(wsContainer, db)

	ws := new(restful.WebService)
	ws.Route(ws.POST("/authorize").
		Consumes("application/x-www-form-urlencoded").
		To(s.authorize))
	wsContainer.Add(ws)

	address := fmt.Sprintf("%s:%s", s.Host, s.Port)
	log.Printf("Listening on %s", address)

	log.Fatalln(http.ListenAndServe(address, wsContainer))
}
开发者ID:jorjeb,项目名称:smart_app,代码行数:35,代码来源:server.go


示例20: init

// connect to the Db
func init() {
	var err error
	Db, err = sqlx.Open("postgres", "user=gwp dbname=gwp password=gwp sslmode=disable")
	if err != nil {
		panic(err)
	}
}
开发者ID:jf,项目名称:gwp,代码行数:8,代码来源:store.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang sqlx.Select函数代码示例发布时间:2022-05-23
下一篇:
Golang sqlx.NewDb函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap