本文整理汇总了Golang中github.com/jmoiron/sqlx.Connect函数的典型用法代码示例。如果您正苦于以下问题:Golang Connect函数的具体用法?Golang Connect怎么用?Golang Connect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Connect函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: Connect
// Connect to the database
func Connect(d Databases) {
var err error
switch d.Type {
case "MySQL":
// Connect to MySQL
if DB, err = sqlx.Connect("mysql", DSN(d.MySQL)); err != nil {
log.Println("SQL Driver Error", err)
}
// Check if is alive
if err := DB.Ping(); err != nil {
log.Println("Database Error", err)
}
case "SQLite":
// Connect to SQLite
if DB, err = sqlx.Connect("sqlite3", d.SQLite.Parameter); err != nil {
log.Println("SQL Driver Error", err)
}
// Check if is alive
if err := DB.Ping(); err != nil {
log.Println("Database Error", err)
}
default:
log.Println("No registered database in config")
}
}
开发者ID:JacksonYY,项目名称:gowebapp,代码行数:29,代码来源:database.go
示例2: OpenDB
// TODO: Instead pass back *sql.DB
func (r *RDPG) OpenDB(dbname string) error {
if r.DB == nil {
u, err := url.Parse(r.URI)
if err != nil {
log.Error(fmt.Sprintf("Failed parsing URI %s err: %s", r.URI, err))
}
u.Path = dbname
r.URI = u.String()
db, err := sqlx.Connect("postgres", r.URI)
if err != nil {
log.Error(fmt.Sprintf("Failed connecting to %s err: %s", rdpgURI, err))
return err
}
r.DB = db
} else {
err := r.DB.Ping()
if err != nil {
db, err := sqlx.Connect("postgres", r.URI)
if err != nil {
log.Error(fmt.Sprintf("Failed connecting to %s err: %s", rdpgURI, err))
proc, _ := os.FindProcess(os.Getpid())
proc.Signal(syscall.SIGTERM)
return err
}
r.DB = db
}
}
return nil
}
开发者ID:longnguyen11288,项目名称:rdpgd,代码行数:30,代码来源:rdpg.go
示例3: SqlRepository
// SqlRepository returns a new sqlRepository or panics if it cannot
func SqlRepository() UserRepository {
settings := settings.NewSettings("settings.json")
db, err := sqlx.Connect(settings.DriverName(), settings.DataSource())
if err != nil {
panic("Error connecting to db: " + err.Error())
}
repo := &sqlRepository{
db: db,
}
datetime := "datetime"
if settings.DriverName() == "postgres" {
datetime = "timestamp with time zone"
}
schema := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS authuser (
key text not null primary key,
name text,
email text,
password text,
created %s,
modified %s,
lastactive %s
);`, datetime, datetime, datetime)
_, err = repo.db.Exec(schema)
return repo
}
开发者ID:nathanborror,项目名称:gommon,代码行数:30,代码来源:sql.go
示例4: sqlxConn
func sqlxConn() *sqlx.DB {
db, err := sqlx.Connect("mysql", mysqlDSN)
if err != nil {
log.Fatalln(err)
}
return db
}
开发者ID:c4pt0r,项目名称:golang-sql-benchmark,代码行数:7,代码来源:sql_benchmark_test.go
示例5: initInjector
func initInjector(cmd *cobra.Command, args []string) {
db, err := sqlx.Connect("postgres", viper.GetString("postgres-url"))
if err != nil {
fail(err)
}
mustProvide(inject.Object{Value: &drivers.DB})
mustProvide(inject.Object{Value: &drivers.Horizon})
mustProvide(inject.Object{Value: &uis.Console})
mustProvide(inject.Object{Value: &drivers.Editor})
mustProvide(inject.Object{Value: &drivers.HTTP})
mustProvide(inject.Object{Value: db})
mustProvide(inject.Object{
Name: "postgres-url",
Value: viper.GetString("postgres-url"),
})
mustProvide(inject.Object{
Name: "horizon-url",
Value: viper.GetString("horizon-url"),
})
if err := injector.Populate(); err != nil {
fail(err)
}
}
开发者ID:nullstyle,项目名称:coinop,代码行数:25,代码来源:internal.go
示例6: initializing
func initializing() {
conn, err := sqlx.Connect("mysql", config.GetConfig().GetString("database.mysql"))
if err != nil {
fmt.Printf("mysql connect err: %+v\n", err)
}
db = conn
}
开发者ID:qianlnk,项目名称:lnkgift,代码行数:7,代码来源:mysql.go
示例7: Connect
func Connect() (*sqlx.DB, error) {
open := os.Getenv("DATABASE_URL")
fmt.Println("connecting to", open)
if parsedURL, err := pq.ParseURL(open); err == nil && parsedURL != "" {
open = parsedURL
}
con, err := sqlx.Connect("postgres", open)
if err != nil {
fmt.Println(err)
return nil, err
}
err = con.Ping()
if err != nil {
fmt.Println(err)
return nil, err
}
return con, err
}
开发者ID:zqzca,项目名称:back,代码行数:25,代码来源:db.go
示例8: init
func init() {
info := config.File.GetStringMap("database")
ConnectionInfo = DatabaseConnection{
info["user"].(string),
info["host"].(string),
info["database"].(string),
}
connString := fmt.Sprintf(
"postgres://%s:@%s/%s?sslmode=disable",
info["user"],
info["host"],
info["database"],
)
Sq = sq.StatementBuilder.PlaceholderFormat(sq.Dollar)
client, err := sqlx.Connect("postgres", connString)
if err != nil {
panic(err)
}
Client = client
println("Connected to Postgres")
}
开发者ID:Pholey,项目名称:distribuTor,代码行数:26,代码来源:db.go
示例9: NewEntityManager
func NewEntityManager(dbType string, url string) (em EntityManager, err error) {
em.db, err = sqlx.Connect(dbType, url)
em.log = logrus.WithFields(logrus.Fields{
"service": "EntityManager",
})
return
}
开发者ID:BIT66COM,项目名称:gateway-server,代码行数:7,代码来源:entity_manager.go
示例10: DBConnect
// DBConnect connects to MySQL database
func DBConnect() (*sqlx.DB, error) {
// Generate connection string using configuration
conn := fmt.Sprintf("%s:%[email protected]/%s", Static.Config.DB.Database, Static.Config.DB.Username, Static.Config.DB.Password)
// Return connection and associated errors
return sqlx.Connect("mysql", conn)
}
开发者ID:nickpresta,项目名称:goat,代码行数:8,代码来源:database.go
示例11: main
func main() {
var (
cfgFile string
role string
)
flag.StringVar(&cfgFile, "c", "./conf/cfg.ini", "config file")
flag.StringVar(&role, "r", "", "server role: scheduler, fetcher etc.")
flag.Parse()
config, err := utils.ReadConfig(cfgFile)
if err == nil {
if role == "scheduler" {
db, _ := sqlx.Connect("mysql", config["scheduler"]["dsn"])
log.Infoln("db stats: ", db.Stats())
scheduler := scheduler.InitScheduler(db, config["scheduler"])
scheduler.Run()
} else if role == "fetcher" {
fetcher := fetcher.InitFetcher(config["fetcher"])
fetcher.Run()
} else {
fmt.Println("unknown role:", role)
}
}
}
开发者ID:zhaozhi406,项目名称:crawler,代码行数:28,代码来源:main.go
示例12: searchHandler
func searchHandler(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
query := req.URL.Query()["q"][0]
cypher := `MATCH (movie:Movie)
WHERE movie.title =~ {0}
RETURN movie.title as title, movie.tagline as tagline, movie.released as released`
db, err := sqlx.Connect("neo4j-cypher", neo4jURL)
if err != nil {
log.Println("error connecting to neo4j:", err)
}
defer db.Close()
movies := []Movie{}
param := "(?i).*" + query + ".*"
err = db.Select(&movies, cypher, param)
if err != nil {
log.Println("error querying search:", err)
}
movieResults := []MovieResult{}
for _, x := range movies {
movieResults = append(movieResults, MovieResult{x})
}
err = json.NewEncoder(w).Encode(movieResults)
if err != nil {
log.Println("error writing search response:", err)
}
}
开发者ID:albertoperdomo,项目名称:cq-example,代码行数:30,代码来源:server.go
示例13: ConnectToDB
func (config *DBConfig) ConnectToDB() *sqlx.DB {
result, err := sqlx.Connect(config.Flavor, config.URI)
if err != nil {
log.Fatal(err)
}
return result
}
开发者ID:alligrader,项目名称:gradebook-backend,代码行数:7,代码来源:util.go
示例14: NewApplication
// NewApplication is the constructor for Application struct.
//
// If testing is true, connects to the "test" database.
func NewApplication(testing bool) (*Application, error) {
u, err := libunix.CurrentUser()
if err != nil {
return nil, err
}
dbname := "forty-thieves"
if testing {
dbname += "-test"
}
dsn := libenv.EnvWithDefault(
"DSN", fmt.Sprintf("postgres://%[email protected]:5432/%s?sslmode=disable", u, dbname))
db, err := sqlx.Connect("postgres", dsn)
if err != nil {
return nil, err
}
cookieStoreSecret := libenv.EnvWithDefault("COOKIE_SECRET", "ittwiP92o0oi6P4i")
app := &Application{}
app.dsn = dsn
app.db = db
app.cookieStore = sessions.NewCookieStore([]byte(cookieStoreSecret))
return app, err
}
开发者ID:topher200,项目名称:forty-thieves,代码行数:30,代码来源:main.go
示例15: init
func init() {
usr, err := user.Current()
if err != nil {
panic(err)
}
workDir := filepath.Join(usr.HomeDir, ".pmusic")
artDir := filepath.Join(workDir, "cArt")
path := filepath.Join(workDir, "music.db3")
err = os.MkdirAll(artDir, 0700)
if err != nil {
panic(err)
}
db, err = sqlx.Connect("sqlite3", path)
if err != nil {
panic(err)
}
dbm = modl.NewDbMap(&db.DB, modl.SqliteDialect{})
dbm.AddTable(Musician{}, "musician").SetKeys(true, "Uid")
dbm.AddTable(Stations{}, "station").SetKeys(true, "Uid")
dbm.AddTable(Album{}, "album").SetKeys(true, "Uid")
dbm.AddTable(Track{}, "track").SetKeys(true, "Uid")
dbm.AddTable(PTimeStamp{}, "ptimestamp").SetKeys(true, "Uid")
err = dbm.CreateTablesIfNotExists()
if err != nil {
panic(err)
}
}
开发者ID:quiznilo,项目名称:PianobarNotification,代码行数:30,代码来源:gr.go
示例16: connect
func (r *RDPG) connect() (db *sqlx.DB, err error) {
db, err = sqlx.Connect("postgres", r.URI)
if err != nil {
log.Error(fmt.Sprintf("rdpg.Node#Connect() %s ! %s", r.URI, err))
}
return db, err
}
开发者ID:longnguyen11288,项目名称:rdpgd,代码行数:7,代码来源:bdr.go
示例17: FetchMetrics
// FetchMetrics interface for mackerelplugin
func (p PostgresPlugin) FetchMetrics() (map[string]interface{}, error) {
db, err := sqlx.Connect("postgres", fmt.Sprintf("user=%s password=%s host=%s port=%s sslmode=%s connect_timeout=%d %s", p.Username, p.Password, p.Host, p.Port, p.SSLmode, p.Timeout, p.Option))
if err != nil {
logger.Errorf("FetchMetrics: %s", err)
return nil, err
}
defer db.Close()
statStatDatabase, err := fetchStatDatabase(db)
if err != nil {
return nil, err
}
statConnections, err := fetchConnections(db)
if err != nil {
return nil, err
}
statDatabaseSize, err := fetchDatabaseSize(db)
if err != nil {
return nil, err
}
stat := make(map[string]interface{})
mergeStat(stat, statStatDatabase)
mergeStat(stat, statConnections)
mergeStat(stat, statDatabaseSize)
return stat, err
}
开发者ID:supercaracal,项目名称:mackerel-agent-plugins,代码行数:30,代码来源:postgres.go
示例18: createDb
func createDb(spec string) (*sqlx.DB, error) {
db, err := sqlx.Connect("mysql", spec+"?parseTime=true&charset=utf8mb4,utf8")
if err != nil {
return nil, err
}
return db, nil
}
开发者ID:petemoore,项目名称:printing3,代码行数:7,代码来源:grabber.go
示例19: newDbForTest
func newDbForTest(t *testing.T) *sqlx.DB {
var err error
pguser, pgpass, pghost, pgport, pgsslmode := os.Getenv("PGUSER"), os.Getenv("PGPASSWORD"), os.Getenv("PGHOST"), os.Getenv("PGPORT"), os.Getenv("PGSSLMODE")
if pguser == "" {
pguser, err = libunix.CurrentUser()
if err != nil {
t.Fatalf("Getting current user should never fail. Error: %v", err)
}
}
if pghost == "" {
pghost = "localhost"
}
if pgport == "" {
pgport = "5432"
}
if pgsslmode == "" {
pgsslmode = "disable"
}
db, err := sqlx.Connect("postgres", fmt.Sprintf("postgres://%[email protected]%v:%v/fpc-test?sslmode=%v&password=%v", pguser, pghost, pgport, pgsslmode, pgpass))
if err != nil {
t.Fatalf("Connecting to local postgres should never fail. Error: %v", err)
}
return db
}
开发者ID:heynickc,项目名称:fpc,代码行数:28,代码来源:base_test.go
示例20: main
func main() {
// this Pings the database trying to connect, panics on error
// use sqlx.Open() for sql.Open() semantics
dbUserName := os.Getenv("DB_USERNAME")
creds := fmt.Sprintf("user=%s dbname=initial sslmode=disable", dbUserName)
fmt.Println(dbUserName)
fmt.Println(creds)
db, err := sqlx.Connect("postgres", creds)
fmt.Println("yay db!")
if err != nil {
fmt.Println(err)
}
// exec the schema or fail; multi-statement Exec behavior varies between
// database drivers; pq will exec them all, sqlite3 won't, ymmv
db.MustExec(schema)
tx := db.MustBegin()
fmt.Println("starting seeding")
tx.MustExec("INSERT INTO users (first_name, last_name, email) VALUES ($1, $2, $3)", "Theo", "Smith-Crespo", "[email protected]")
tx.MustExec("INSERT INTO users (first_name, last_name, email) VALUES ($1, $2, $3)", "Janice", "Smith", "[email protected]")
tx.MustExec("INSERT INTO users (first_name, last_name, email) VALUES ($1, $2, $3)", "Alvin", "Crespo", "[email protected]")
tx.Commit()
fmt.Println("ending seeding")
}
开发者ID:Avancement,项目名称:inital,代码行数:28,代码来源:seeds.go
注:本文中的github.com/jmoiron/sqlx.Connect函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论