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


Golang sqlx.Connect函數代碼示例

本文整理匯總了Golang中github.com/jmoiron/sqlx.Connect函數的典型用法代碼示例。如果您正苦於以下問題:Golang Connect函數的具體用法?Golang Connect怎麽用?Golang Connect使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Connect函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


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