//数据库连接 func Connect() { var dns string db_type := beego.AppConfig.String("db_type") db_host := beego.AppConfig.String("db_host") db_port := beego.AppConfig.String("db_port") db_user := beego.AppConfig.String("db_user") db_pass := beego.AppConfig.String("db_pass") db_name := beego.AppConfig.String("db_name") db_path := beego.AppConfig.String("db_path") db_sslmode := beego.AppConfig.String("db_sslmode") switch db_type { case "mysql": orm.RegisterDriver("mysql", orm.DR_MySQL) dns = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", db_user, db_pass, db_host, db_port, db_name) break case "postgres": orm.RegisterDriver("postgres", orm.DR_Postgres) dns = fmt.Sprintf("dbname=%s host=%s user=%s password=%s port=%s sslmode=%s", db_name, db_host, db_user, db_pass, db_port, db_sslmode) case "sqlite3": orm.RegisterDriver("sqlite3", orm.DR_Sqlite) if db_path == "" { db_path = "./" } dns = fmt.Sprintf("%s%s.db", db_path, db_name) break default: beego.Critical("Database driver is not allowed:", db_type) } orm.RegisterDataBase("default", db_type, dns) }
func init() { dbname := "default" runmode := beego.AppConfig.String("runmode") datasource := beego.AppConfig.String("datasource") switch runmode { case "prod": //orm.RegisterDriver("postgres", orm.DR_Postgres) //orm.RegisterDataBase(dbname, "postgres", datasource, 30) //orm.SetMaxIdleConns(dbname, 100) //orm.SetMaxOpenConns(dbname, 100) orm.RegisterDriver("mysql", orm.DRMySQL) orm.RegisterDataBase(dbname, "mysql", datasource) case "dev": orm.RegisterDriver("mysql", orm.DRMySQL) orm.RegisterDataBase(dbname, "mysql", datasource) default: //orm.RegisterDataBase(dbname, "sqlite3", datasource) orm.RegisterDriver("mysql", orm.DRMySQL) orm.RegisterDataBase(dbname, "mysql", datasource) } orm.DefaultTimeLoc = time.FixedZone("Asia/Tokyo", 9*60*60) force, verbose := false, true err := orm.RunSyncdb(dbname, force, verbose) if err != nil { panic(err) } // orm.RunCommand() }
//初始化mysql或postgresql数据库,配置参数如下 // // db_type 数据库类型,mysql或postgres(mysql) // // db_host 数据库主机地址(127.0.0.1) // // db_port 数据库端口(3306) // // db_user 数据库用户(root) // // db_pass 数据库密码 // // db_name 数据库名 // // db_sslmode 是否SSL模式连接,仅用于postgresql(disable) func InitDB() { if beego.BConfig.RunMode == "dev" { beego.Info("initiating db") } var dsn string db_type := beego.AppConfig.DefaultString("db_type", "mysql") db_host := beego.AppConfig.DefaultString("db_host", "127.0.0.1") db_port := beego.AppConfig.DefaultString("db_port", "3306") db_user := beego.AppConfig.DefaultString("db_user", "root") db_pass := beego.AppConfig.DefaultString("db_pass", "") db_name := beego.AppConfig.String("db_name") //db_path := beego.AppConfig.String("db_path") db_sslmode := beego.AppConfig.DefaultString("db_sslmode", "disable") switch db_type { case "mysql": orm.RegisterDriver("mysql", orm.DRMySQL) dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", db_user, db_pass, db_host, db_port, db_name) break case "postgres": orm.RegisterDriver("postgres", orm.DRPostgres) dsn = fmt.Sprintf("dbname=%s host=%s user=%s password=%s port=%s sslmode=%s", db_name, db_host, db_user, db_pass, db_port, db_sslmode) // case "sqlite3": // orm.RegisterDriver("sqlite3", orm.DR_Sqlite) // if db_path == "" { // db_path = "./" // } // dns = fmt.Sprintf("%s%s.db", db_path, db_name) // break default: panic("Database driver is not allowed:" + db_type) } orm.RegisterDataBase("default", db_type, dsn) }
func initDb(dbType string) { orm.DefaultRowsLimit = -1 switch dbType { case "mysql": orm.RegisterDriver("mysql", orm.DRMySQL) case "postgres": orm.RegisterDriver("postgres", orm.DRPostgres) default: panic("not specific db Type") } var initOk bool configerMap, _ := config.GlobalConfiger.Map(dbType) for key, value := range configerMap { if key == "default" { initOk = true } if err := orm.RegisterDataBase(key, dbType, value.(string)); err != nil { panic(err) } } if !initOk { panic("a database instance called default must be inited") } if config.GlobalConfiger.String("runmode") == "dev" { orm.Debug = true } }
// initialize the db driver and config func InitDB(c *gokits.Crypto) { if dbinited { return } // 设置为 UTC 时间 orm.DefaultTimeLoc = time.UTC orm.Debug = false web, err := macaron.Config().GetSection("web") if err != nil { panic(err) } webcfg = web sqllog := webcfg.Key("sqllog").String() // log the sql string if "on" == sqllog { orm.Debug = true } dbtype = web.Key("dbtype").String() log.Debugf("DB type is %s", dbtype) dbcfg, err := macaron.Config().GetSection(dbtype) if err != nil { panic(err) } switch dbtype { case "mysql": var username string = dbcfg.Key("username").String() if username, err = c.DecryptStr(username); err != nil { panic(err) } var password string = dbcfg.Key("password").String() if password, err = c.DecryptStr(password); err != nil { panic(err) } url := dbcfg.Key("url").String() maxidle = dbcfg.Key("maxidle").MustInt(2) maxconn = dbcfg.Key("maxconn").MustInt(2) dburl = username + ":" + password + "@" + url orm.RegisterDriver(dbtype, orm.DR_MySQL) case "sqlite": dburl = dbcfg.Key("url").String() dbtype = "sqlite3" orm.RegisterDriver(dbtype, orm.DR_Sqlite) } dbinited = true }
func init() { dbname := "default" // 数据库别名 dbtype := beego.AppConfig.String("dbtype") dbcfg, err := beego.AppConfig.GetSection(dbtype) if err != nil { panic(err) } // 统一采用 UTC 时间 orm.DefaultTimeLoc = time.UTC orm.Debug = true switch dbtype { case "mysql": var username string = dbcfg["username"] if username, err = utils.AesDecrypt(username); err != nil { panic(err) } var password string = dbcfg["password"] if password, err = utils.AesDecrypt(password); err != nil { panic(err) } url := dbcfg["url"] maxidle, _ := strconv.Atoi(dbcfg["maxidle"]) maxconn, _ := strconv.Atoi(dbcfg["maxconn"]) orm.RegisterDriver("mysql", orm.DR_MySQL) orm.RegisterDataBase(dbname, "mysql", username+":"+password+"@"+url, maxidle, maxconn) case "sqlite": url := dbcfg["url"] orm.RegisterDriver("sqlite3", orm.DR_Sqlite) orm.RegisterDataBase(dbname, "sqlite3", url) } orm.RegisterModel(new(User), new(UserBind), new(UserStats)) orm.RegisterModel(new(Question), new(Reply), new(QuestionMark), new(AnswerMark)) orm.RegisterModel(new(Category)) orm.RegisterModel(new(Blog)) orm.RegisterModel(new(Comment)) force := false // drop table 后再建表 verbose, _ := beego.AppConfig.Bool("SqlLogOn") // 打印执行过程 // 遇到错误立即返回 err = orm.RunSyncdb(dbname, force, verbose) if err != nil { fmt.Println(err) } }
//连接数据库 func ConnectDB() { db_type := beego.AppConfig.String("db::type") db_host := beego.AppConfig.String("db::host") db_port := beego.AppConfig.String("db::port") db_user := beego.AppConfig.String("db::user") db_pass := beego.AppConfig.String("db::pass") db_name := beego.AppConfig.String("db::name") db_path := beego.AppConfig.String("db::path") db_sslmode := beego.AppConfig.String("db::sslmode") var dsn string switch db_type { case "mysql": orm.RegisterDriver("mysql", orm.DR_MySQL) dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", db_user, db_pass, db_host, db_port, db_name) dsn += "&loc=Asia%2FShanghai" break case "postgres": orm.RegisterDriver("postgres", orm.DR_Postgres) dsn = fmt.Sprintf("dbname=%s host=%s user=%s password=%s port=%s sslmode=%s", db_name, db_host, db_user, db_pass, db_port, db_sslmode) case "sqlite3": orm.RegisterDriver("sqlite3", orm.DR_Sqlite) if db_path == "" { db_path = "./" } dsn = fmt.Sprintf("%s%s.db", db_path, db_name) break default: beego.Critical("Database driver not support: ", db_type) } orm.RegisterDataBase("default", db_type, dsn) //打印查询日志 orm.Debug, _ = beego.AppConfig.Bool("db::orm_debug") o = orm.NewOrm() // 数据库别名 name := "default" // 不强制重新建数据库 force := false // 打印执行过程 verbose := true // 遇到错误立即返回 err := orm.RunSyncdb(name, force, verbose) if err != nil { beego.Error(err) } }
func RegistDB() { host := beego.AppConfig.String("DBhost") dataSource := "root:arvin@(" + host + ":3306)/test?charset=utf8" orm.RegisterModel(new(Category), new(Topic), new(Reply)) orm.RegisterDriver("mysql", orm.DRMySQL) orm.RegisterDataBase("default", "mysql", dataSource) }
func init() { orm.Debug = true orm.RegisterDriver("sqlite", orm.DR_Sqlite) orm.RegisterDataBase("default", "sqlite3", "./gowebssh.db") }
func init() { /* 로그기록 */ //NewLogger(10000) beego.SetLogger("file", `{"filename":"server.log"}`) /* 데이타베이스 드라이브 설정 */ orm.RegisterDriver("mysql", orm.DR_MySQL) orm.RegisterDataBase("default", "mysql", "root:Kim616294.@/cluber?charset=utf8&loc=Asia%2FSeoul") /* 데이타베이스 테이블 등록 */ orm.RegisterModel(new(models.User)) orm.RegisterModel(new(models.Log)) orm.RegisterModel(new(models.Contents)) // 사용 데이타베이스 name := "default" // 서버 시작시 테이블 재생성 force := false // SQL 로그 확인 verbose := true // 데이타베이스를 동기화 하고 에러 발생시 err 에 에러내용 입력 err := orm.RunSyncdb(name, force, verbose) if err != nil { fmt.Println(err) } }
func connectDB() { orm.RegisterDriver("mysql", orm.DR_MySQL) name := utils.GetConf().String("db::name") user := utils.GetConf().String("db::user") pass := utils.GetConf().String("db::pass") host := utils.GetConf().String("db::host") port := utils.GetConf().String("db::port") //data source name // dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, pass, host, port, name) dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&loc=Local", user, pass, host, port, name) orm.RegisterDataBase("default", "mysql", dsn) orm.RegisterModel(new(User), new(Project), new(ProjectLog)) orm.RegisterModel(new(Company), new(Job), new(Progress)) orm.RegisterModel(new(File), new(JobComplaint), new(JobProgress)) orm.RegisterModel(new(JobValid), new(JobClaim), new(JobSubmit)) orm.RegisterModel(new(UserLogin), new(JobAssign)) orm.RegisterModel(new(JobHistory), new(JobComplaintReply)) orm.RegisterModel(new(Require)) db = orm.NewOrm() setMaxIdleConns() }
func init() { orm.RegisterDriver("mysql", orm.DR_MySQL) orm.RegisterDataBase("default", "mysql", "user:Passwd@/ayp?charset=utf8") orm.RegisterModel(new(models.Articulos), new(models.Categoria), new(models.Proveedor), new(models.Usuarios), new(models.Empresa)) }
func init() { orm.RegisterDriver("mysql", orm.DR_MySQL) orm.RegisterDataBase("default", "mysql", "root:root@tcp(localhost:8889)/MtimeCI?charset=utf8&loc=Asia%2FShanghai") orm.Debug = true }
func main() { setting.Initialize() beego.SetLogFuncCall(true) beego.SetViewsPath("views") if setting.IsProMode { beego.Info(setting.PostgresMigrateConnection) //auto migrate db //todo: we may want to disable this later //dbMigrate() } else { beego.Info("Develment mode enabled") } dbMigrate() beego.Info(beego.BConfig.AppName, setting.APP_VER, setting.AppUrl) testOnly() //todo:remove this //dev directory listing if !setting.IsProMode { beego.SetStaticPath("/assets", "static/dist/assets") beego.BConfig.WebConfig.DirectoryIndex = true } orm.RegisterDriver("postgres", orm.DRPostgres) orm.RegisterDataBase("default", "postgres", setting.PostgresConnection) services.Register() orm.RunCommand() orm.Debug = true controllers.RegisterControllers() if beego.BConfig.RunMode == "dev" { // beego.Router("/test/:tmpl(mail/.*)", new(base.TestRouter)) } beego.Run() }
func init() { //For version 1.6 //orm.DRMySQL //orm.DRSqlite //orm.DRPostgres // < 1.6 //orm.DR_MySQL //orm.DR_Sqlite //orm.DR_Postgres // 参数1 driverName // 参数2 数据库类型 // 这个用来设置 driverName 对应的数据库类型 // mysql / sqlite3 / postgres 这三种是默认已经注册过的,所以可以无需设置 orm.RegisterDriver("mysql", orm.DRMySQL) // 参数1 数据库的别名,用来在ORM中切换数据库使用 // 参数2 driverName // 参数3 对应的链接字符串 orm.RegisterDataBase("default", "mysql", "root:admin@/sport_collage?charset=utf8") // 参数4(可选) 设置最大空闲连接 // 参数5(可选) 设置最大数据库连接 (go >= 1.2) //maxIdle := 30 //maxConn := 30 //orm.RegisterDataBase("default", "mysql", "root:root@/orm_test?charset=utf8", maxIdle, maxConn) orm.RunSyncdb("default", false, false) }
func init() { // orm.RegisterDataBase("default", "mysql", "root:1234@tcp(localhost:3306)/qq?charset=utf8") orm.RegisterDataBase("default", "mysql", "cdb_outerroot:root1234@tcp(55c354e17de4e.sh.cdb.myqcloud.com:7276)/qq?charset=utf8") orm.RegisterDriver("mysql", orm.DR_MySQL) orm.RegisterModel(new(User), new(Profile), new(Userz), new(Friends)) ORM = orm.NewOrm() }
func initORM() { if ormInitiated { return } appConf, err := config.NewConfig("ini", "conf/app.conf") if err != nil { panic(err) } dbAddr := appConf.String("admin::dbAddr") dbUser := appConf.String("admin::dbUser") dbPass := appConf.String("admin::dbPass") controllers.ALI_YUN_AK_ID = appConf.String("admin::akId") controllers.ALI_YUN_AK_KEY = appConf.String("admin::akKey") controllers.QQ_OAUTH_CONSUMER_KEY = appConf.String("admin::qqOAuthConsumerKey") clientId := appConf.String("admin::clientId") clientSecret := appConf.String("admin::clientSecret") controllers.BASIC_AUTH_AUTHORIZATION = utils.Base64(clientId + ":" + clientSecret) controllers.VISITOR_TOKEN = appConf.String("admin::visitorToken") orm.RegisterDriver("mymysql", orm.DRMySQL) conn := fmt.Sprintf("%s:%s@tcp(%s)/beego_unit_test?charset=utf8mb4", dbUser, dbPass, dbAddr) orm.RegisterDataBase("default", "mysql", conn) ormInitiated = true }
func init() { duangcfg, err := config.NewConfig("ini", "conf/duang.conf") if err != nil { fmt.Println(err) return } orm.RegisterDriver("mysql", orm.DR_MySQL) orm.RegisterDataBase("default", "mysql", fmt.Sprintf("%s:%s@%s/%s?charset=utf8", duangcfg.String("db_user"), duangcfg.String("db_pass"), duangcfg.String("db_addr"), duangcfg.String("db_name"))) orm.RegisterModel( new(Unit), new(UnitParameter), new(Dockerd), new(Ip), new(Container), //new(Frontend), //new(Backend), ) force, err := duangcfg.Bool("db_dropifexist") if err != nil { force = false } verbose := true err = orm.RunSyncdb("default", force, verbose) if err != nil { beego.Error(err) } }
func init() { orm.RegisterDriver("mymysql", orm.DR_MySQL) orm.RegisterDataBase("default", "mymysql", "tcp:127.0.0.1:3306*test/root/mysql") orm.Debug = true orm.RegisterModel(new(Entity)) orm.BootStrap() }
func init() { //读取配置文件信息 settings := func(path string) map[string]string { return goutils.NewConfig().Load(path).GlobalContent() }("conf/app.conf") //获取settings中的信息 dbinfo, ok := settings["DBINFO"] if !ok { log.Fatal("not found DBINFO in config file") } orm.RegisterDriver("mysql", orm.DRMySQL) orm.RegisterDataBase("default", "mysql", dbinfo) orm.RegisterModel( new(First), new(Second), new(System), new(Userinfo), new(Userlog), new(Novel), new(Content), new(Collectrank), new(Clickrank), new(Recommend), ) }
func init() { orm.RegisterDriver("mysql", orm.DR_MySQL) err := orm.RegisterDataBase("default", "mysql", global.C.MySqlUrl) if err != nil { fmt.Println(err) } }
// Init will initialize database to create tables automatically. func init() { // Registry archci database models. models.RegisterModels() // Initialize database with environment variables. server := "" username := "******" password := "******" database := "mysql" if os.Getenv(ENV_MYSQL_SERVER) != "" { server = os.Getenv(ENV_MYSQL_SERVER) } if os.Getenv(ENV_MYSQL_USERNAME) != "" { username = os.Getenv(ENV_MYSQL_USERNAME) } if os.Getenv(ENV_MYSQL_PASSWORD) != "" { password = os.Getenv(ENV_MYSQL_PASSWORD) } if os.Getenv(ENV_MYSQL_DATABASE) != "" { database = os.Getenv(ENV_MYSQL_DATABASE) } // The datasource looks like "root:root@/archci?charset=utf8". DATASOURCE := username + ":" + password + "@" + server + "/" + database + "?charset=utf8" fmt.Println("Connect to database with " + DATASOURCE) orm.RegisterDriver(MYSQL_DRIVER, orm.DR_MySQL) orm.RegisterDataBase("default", MYSQL_DRIVER, DATASOURCE, 30) orm.RunSyncdb("default", false, true) }
func init() { //register all tables orm.RegisterModel(new(Userinfo), new(Admininfo), new(Deviceinfo), new(Historyinfo), new(Command), new(OperationRecord), new(Alarm), new(Script)) //register mysql driver err := orm.RegisterDriver("mysql", orm.DR_MySQL) if err != nil { beego.Critical(err) } //register default database dbIp := beego.AppConfig.String("DbIp") dbPort := beego.AppConfig.String("DbPort") dbName := beego.AppConfig.String("DbName") dbUser := beego.AppConfig.String("DbUser") dbPassword := beego.AppConfig.String("DbPassword") dbUrl := dbUser + ":" + dbPassword + "@tcp(" + dbIp + ":" + dbPort + ")/" + dbName + "?charset=utf8&loc=Asia%2FShanghai" beego.Debug("dbUrl=", dbUrl) err = orm.RegisterDataBase("default", "mysql", dbUrl) if err != nil { beego.Critical(err) } //orm.RegisterDataBase("default", "mysql", "root:autelan@/lte_test?charset=utf8&&loc=Asia%2FShanghai") orm.SetMaxIdleConns("default", 30) orm.SetMaxOpenConns("default", 30) }
func init() { orm.RegisterDriver("mysql", orm.DR_MySQL) // orm.RegisterDataBase("local", "mysql", "root:1234@tcp(localhost:3306)/os?charset=utf8") orm.RegisterDataBase("default", "mysql", "cdb_outerroot:root1234@tcp(55c354e17de4e.sh.cdb.myqcloud.com:7276)/os?charset=utf8") orm.RegisterModel(new(Groups), new(User), new(Grel), new(Message), new(Item), new(Friends), new(Login)) ORM = orm.NewOrm() }
//InitDB initializes the database func InitDB() { orm.RegisterDriver("mysql", orm.DRMySQL) addr := os.Getenv("MYSQL_HOST") port := os.Getenv("MYSQL_PORT") username := os.Getenv("MYSQL_USR") password := os.Getenv("MYSQL_PWD") log.Debugf("db url: %s:%s, db user: %s", addr, port, username) dbStr := username + ":" + password + "@tcp(" + addr + ":" + port + ")/registry" ch := make(chan int, 1) go func() { var err error var c net.Conn for { c, err = net.DialTimeout("tcp", addr+":"+port, 20*time.Second) if err == nil { c.Close() ch <- 1 } else { log.Errorf("failed to connect to db, retry after 2 seconds :%v", err) time.Sleep(2 * time.Second) } } }() select { case <-ch: case <-time.After(60 * time.Second): panic("Failed to connect to DB after 60 seconds") } err := orm.RegisterDataBase("default", "mysql", dbStr) if err != nil { panic(err) } }
func init() { orm.RegisterDriver("mysql", orm.DR_MySQL) orm.RegisterDataBase("default", "mysql", "root:1234@tcp(localhost:3306)/os?charset=utf8") orm.RegisterModel(new(Groups), new(User), new(Grel)) ORM = orm.NewOrm() orm.Debug = true }
func init() { orm.RegisterDriver("mysql", orm.DRMySQL) orm.RegisterDataBase("go", "mysql", "cmsuser:cms@tcp(10.255.223.241:3306)/bookbar_fuzuokui?charset=utf8") orm.SetMaxIdleConns("go", 30) //设置数据库最大空闲连接 orm.SetMaxOpenConns("go", 30) //设置数据库最大连接数 orm.RegisterModel(new(GoBar)) }
func dbInit() { orm.RegisterModel(new(UserInfo), new(UserStatus), new(UserRecord)) //register mysql driver err := orm.RegisterDriver("mysql", orm.DR_MySQL) if err != nil { beego.Critical(err) } //register default database if !localSwitch { orm.RegisterDataBase("default", "mysql", "autelan:Autelan1202@tcp(rdsrenv7vrenv7v.mysql.rds.aliyuncs.com:3306)/umsdb?charset=utf8&&loc=Asia%2FShanghai") } else { dbIp := beego.AppConfig.String("DbIp") dbPort := beego.AppConfig.String("DbPort") dbName := beego.AppConfig.String("DbName") dbUser := beego.AppConfig.String("DbUser") dbPassword := beego.AppConfig.String("DbPassword") dbUrl := dbUser + ":" + dbPassword + "@tcp(" + dbIp + ":" + dbPort + ")/" + dbName + "?charset=utf8&loc=Asia%2FShanghai" beego.Debug("dbUrl=", dbUrl) err = orm.RegisterDataBase("default", "mysql", dbUrl) if err != nil { beego.Critical(err) } } orm.SetMaxIdleConns("default", 30) orm.SetMaxOpenConns("default", 30) ormer = orm.NewOrm() }
func RegistDB() { orm.RegisterModel(new(User), new(Article), new(Stream)) orm.RegisterDriver("mysql", orm.DR_MySQL) orm.RegisterDataBase("default", "mysql", "root:mysql@/newblog?charset=utf8") orm.RunSyncdb("default", false, true) }
func init() { orm.RegisterModelWithPrefix("llb_", new(Admin)) orm.RegisterDriver("mysql", orm.DR_MySQL) orm.RegisterDataBase("default", "mysql", "root:@/liaoliaoba?charset=utf8") }