本文整理汇总了Golang中github.com/jmoiron/sqlx.NewDb函数的典型用法代码示例。如果您正苦于以下问题:Golang NewDb函数的具体用法?Golang NewDb怎么用?Golang NewDb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewDb函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: GetRaw
// GetRaw runs the provided postgres query and args against this sqlquery's db.
func (q SqlQuery) GetRaw(ctx context.Context, query string, args []interface{}, dest interface{}) error {
db := sqlx.NewDb(q.DB, "postgres")
log.WithField(ctx, "sql", query).Info("query sql")
log.WithField(ctx, "args", args).Debug("query args")
return db.Get(dest, query, args...)
}
示例2: Open
func (d *DB) Open() error {
conf := pgx.ConnPoolConfig{
ConnConfig: pgx.ConnConfig{
Host: d.config.Host,
Port: uint16(d.config.Port),
User: d.config.Username,
Password: d.config.Password,
Database: d.config.Database,
Logger: d.config.Logger,
},
MaxConnections: d.config.MaxConnections,
}
p, err := pgx.NewConnPool(conf)
if err != nil {
return err
}
db, err := stdlib.OpenFromConnPool(p)
if err != nil {
return err
}
dbx := sqlx.NewDb(db, "pgx")
d.queryer = queryer{impl: dbx}
return nil
}
示例3: init
func init() {
var err error
db, err = sql.Open("sqlite3", ":memory:")
if err != nil {
panic(err)
}
db.Exec("DROP TABLE users;")
dbx = sqlx.NewDb(db, "sqlite3")
ddl := []string{CreateUserStmt}
for _, stmt := range ddl {
_, err = db.Exec(stmt)
if err != nil {
panic(err)
}
}
for i := 0; i < 100; i++ {
user := &User{}
user.Name = randomdata.FullName(randomdata.RandomGender)
user.Email = randomdata.Email()
user.Pass = "pa55word"
user.Created = time.Now().Unix()
user.Updated = time.Now().Unix()
err := InsertUser(db, InsertUserStmt, user)
if err != nil {
panic(err)
}
}
}
示例4: server
func server(config config, db *sql.DB) *echo.Echo {
dbx := sqlx.NewDb(db, "postgres")
exec := echo.New()
if !config.Production {
exec.Debug()
}
exec.Use(mw.Logger())
exec.Use(mw.Recover())
exec.Use(mw.Gzip())
exec.Get("/status", func(c *echo.Context) error {
return c.NoContent(http.StatusOK)
})
leadHandler := lead.NewHandler(datastores.NewLead(dbx))
exec.Post("/lead", leadHandler.Create)
exec.Get("/lead/:hashCode", leadHandler.CountByInvites)
assetHandler := http.FileServer(rice.MustFindBox("static").HTTPBox())
exec.Get("/", func(c *echo.Context) error {
assetHandler.ServeHTTP(c.Response().Writer(), c.Request())
return nil
})
exec.Get("/static/*", func(c *echo.Context) error {
http.StripPrefix("/static/", assetHandler).
ServeHTTP(c.Response().Writer(), c.Request())
return nil
})
return exec
}
示例5: Connect
//Connect connec to the db
func (db *DB) Connect(sqlType, conn string, maxOpenConn int) (err error) {
db.sqlType = sqlType
db.connectionString = conn
rawDB, err := sql.Open(db.sqlType, db.connectionString)
if err != nil {
return err
}
rawDB.SetMaxOpenConns(maxOpenConn)
rawDB.SetMaxIdleConns(maxOpenConn)
db.DB = sqlx.NewDb(rawDB, db.sqlType)
if db.sqlType == "sqlite3" {
db.DB.Exec("PRAGMA foreign_keys = ON;")
}
for i := 0; i < retryDB; i++ {
err = db.DB.Ping()
if err == nil {
return nil
}
time.Sleep(retryDBWait * time.Second)
log.Info("Retrying db connection... (%s)", err)
}
return fmt.Errorf("Failed to connect db")
}
示例6: TestMain
func TestMain(m *testing.M) {
var err error
test.db, err = sql.Open("sqlite3", ":memory:")
panicIfErr(err)
_, err = test.db.Exec("CREATE TABLE users(a, b UNIQUE)")
panicIfErr(err)
_, err = test.db.Exec("INSERT INTO users VALUES(1, 2)")
panicIfErr(err)
test.dbx = sqlx.NewDb(test.db, "sqlite3")
test.dbgorm, err = gorm.Open("sqlite3", ":memory:")
panicIfErr(err)
user := &User{"1", "2"}
test.dbgorm.CreateTable(user)
test.dbgorm.Create(user)
err = orm.RunSyncdb("default", true, false)
panicIfErr(err)
test.dbbeegoorm = orm.NewOrm()
beeuser := &BeeUser{A: "1", B: "2"}
test.dbbeegoorm.Insert(beeuser)
os.Exit(m.Run())
}
示例7: NewTestDB
// NewTestDB connects to the default DBMS, creates a new database using testdb,
// and loads the application's schema.
func NewTestDB() (*testdb.TestDB, *sqlx.DB, error) {
stmts, err := readSQL("../schema.sql")
if err != nil {
return nil, nil, err
}
tdb, err := testdb.Open(DriverName, DefaultDataSource+" dbname=postgres")
if err != nil {
return nil, nil, err
}
db, err := sql.Open(DriverName, DefaultDataSource+" dbname="+tdb.Name())
if err != nil {
tdb.Close()
return nil, nil, err
}
for _, stmt := range stmts {
if _, err := db.Exec(stmt); err != nil {
db.Close()
tdb.Close()
return nil, nil, fmt.Errorf("%#v\nExecuting: %s", err, stmt)
}
}
dbx := sqlx.NewDb(db, DriverName)
dbx.MapperFunc(MapperFunc())
return tdb, dbx, nil
}
示例8: TestCatalogueServiceTags
func TestCatalogueServiceTags(t *testing.T) {
logger = log.NewLogfmtLogger(os.Stderr)
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening stub database connection", err)
}
defer db.Close()
sqlxDB := sqlx.NewDb(db, "sqlmock")
var cols []string = []string{"name"}
mock.ExpectQuery("SELECT name FROM tag").WillReturnRows(sqlmock.NewRows(cols).
AddRow(tags[0]).
AddRow(tags[1]).
AddRow(tags[2]))
s := NewCatalogueService(sqlxDB, logger)
have, err := s.Tags()
if err != nil {
t.Errorf("Tags(): %v", err)
}
if !reflect.DeepEqual(tags, have) {
t.Errorf("Tags(): want %v, have %v", tags, have)
}
}
示例9: Server
func Server(db *sql.DB) *echo.Echo {
dbx := sqlx.NewDb(db, "postgres")
e := echo.New()
e.Post("/books/:name", createBook(dbx))
e.Get("/books", listBooks(dbx))
return e
}
示例10: NewDbMap
// NewDbMap returns a new DbMap using the db connection and dialect.
func NewDbMap(db *sql.DB, dialect Dialect) *DbMap {
return &DbMap{
Db: db,
Dialect: dialect,
Dbx: sqlx.NewDb(db, dialect.DriverName()),
mapper: reflectx.NewMapperFunc("db", sqlx.NameMapper),
}
}
示例11: InitDB
// Setup the database to be shared across the app.
func (c *DatabaseConfig) InitDB() error {
vdb, err := c.NewVersionedDB()
if err != nil {
return err
}
DB = sqlx.NewDb(vdb.DB, database.DEFAULT_DRIVER)
return nil
}
示例12: NewDB
func NewDB(dsn string) *DB {
if dsn == "" {
dsn = "testing:[email protected](localhost:3306)/testing?charset=utf8&parseTime=True"
}
sqlxDb := sqlx.NewDb(connect("mysql", dsn), "mysql")
return &DB{*sqlxDb, newStmtCache()}
}
示例13: NewDatastore
// NewDatastore returns a new Datastore
func NewDatastore(db *sql.DB) datastore.Datastore {
dbx := sqlx.NewDb(db, "postgres")
return struct {
*Cepstore
}{
NewCepstore(dbx),
}
}
示例14: Get
func (q SqlQuery) Get(ctx context.Context, sql sq.SelectBuilder, dest interface{}) error {
db := sqlx.NewDb(q.DB, "postgres")
sql = sql.PlaceholderFormat(sq.Dollar)
query, args, err := sql.ToSql()
if err != nil {
return err
}
return db.Get(dest, query, args...)
}
示例15: SelectRaw
// SelectRaw runs the provided postgres query and args against this sqlquery's db.
func (q SqlQuery) SelectRaw(ctx context.Context, query string, args []interface{}, dest interface{}) error {
db := sqlx.NewDb(q.DB, "postgres")
log.WithField(ctx, "sql", query).Info("query sql")
log.WithField(ctx, "args", args).Debug("query args")
err := db.Select(dest, query, args...)
if err != nil {
err = errors.Wrap(err, 1)
}
return err
}