示例#1
0
文件: models.go 项目: jcfrank/gogs
func NewTestEngine(x *xorm.Engine) (err error) {
	switch DbCfg.Type {
	case "mysql":
		x, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
			DbCfg.User, DbCfg.Pwd, DbCfg.Host, DbCfg.Name))
	case "postgres":
		var host, port = "127.0.0.1", "5432"
		fields := strings.Split(DbCfg.Host, ":")
		if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
			host = fields[0]
		}
		if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
			port = fields[1]
		}
		cnnstr := fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s",
			DbCfg.User, DbCfg.Pwd, host, port, DbCfg.Name, DbCfg.SslMode)
		//fmt.Println(cnnstr)
		x, err = xorm.NewEngine("postgres", cnnstr)
	case "sqlite3":
		if !EnableSQLite3 {
			return fmt.Errorf("Unknown database type: %s", DbCfg.Type)
		}
		os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
		x, err = xorm.NewEngine("sqlite3", DbCfg.Path)
	default:
		return fmt.Errorf("Unknown database type: %s", DbCfg.Type)
	}
	if err != nil {
		return fmt.Errorf("models.init(fail to conntect database): %v", err)
	}
	return x.Sync(tables...)
}
示例#2
0
文件: models.go 项目: xqbumu/zenpress
func ConDb() (*xorm.Engine, error) {
	switch {

	case DataType == "memory":
		return xorm.NewEngine("tidb", "memory://tidb/tidb")

	case DataType == "goleveldb":
		return xorm.NewEngine("tidb", "goleveldb://./data/goleveldb")

	case DataType == "boltdb":
		return xorm.NewEngine("tidb", "boltdb://./data/boltdb")

	case DataType == "mysql":
		return xorm.NewEngine("mysql", "root:YouPass@/db?charset=utf8")
		//return xorm.NewEngine("mysql", "root:YouPass@/db?charset=utf8")

	case DataType == "postgres":
		return xorm.NewEngine("postgres", "user=postgres password=jn!@#$%^&* dbname=pgsql sslmode=disable")
		//return xorm.NewEngine("postgres", "user=postgres password=jn!@#$%^&* dbname=pgsql sslmode=disable")

		// "user=postgres password=jn!@#$%^&* dbname=yougam sslmode=disable maxcons=10 persist=true"
		//return xorm.NewEngine("postgres", "host=110.76.39.205 user=postgres password=jn!@#$%^&* dbname=yougam sslmode=disable")
		//return xorm.NewEngine("postgres", "host=127.0.0.1 port=6432 user=postgres password=jn!@#$%^&* dbname=yougam sslmode=disable")
	}
	return nil, errors.New("尚未设定数据库连接")
}
示例#3
0
文件: tidb_test.go 项目: go-xorm/tidb
func newTidbEngine(storeType string) (*xorm.Engine, error) {
	if storeType == "memory" {
		return xorm.NewEngine("tidb", storeType+"://tidb/tidb?parseTime=true")
	}

	os.Remove("./tidb_" + storeType)
	return xorm.NewEngine("tidb", storeType+"://./tidb_"+storeType+"/tidb?parseTime=true")
}
示例#4
0
func InitDB() (err error) {
	// utils.LoadConfig("conf/app.conf")
	utils.LoadConfig("conf/app-local.conf")
	// utils.LoadConfig("conf/app-skytap.conf")

	// appname = goTestLinkReport
	// httpport = 8080
	// runmode = dev
	// appname = utils.Cfg.MustValue("server", key, ...)

	// dbtype = mysql
	// host = 127.0.0.1
	// port = 3306
	// name = report
	// user = root
	// pwd = 123123
	// # SSLMODE = false
	dbtype := utils.Cfg.MustValue("db", "dbtype")
	host := utils.Cfg.MustValue("db", "host")
	port := utils.Cfg.MustValue("db", "port")
	name := utils.Cfg.MustValue("db", "name")
	user := utils.Cfg.MustValue("db", "user")
	pwd := utils.Cfg.MustValue("db", "pwd")
	ssl := utils.Cfg.MustValue("db", "ssl")

	switch dbtype {
	case "mysql":
		// connstr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8",
		// 	user, pwd, host, port, name)
		connstr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8",
			user, pwd, host, port, name)
		fmt.Errorf(connstr)
		orm, err = xorm.NewEngine("mysql", connstr)
		if err != nil {
			beego.Debug(fmt.Sprintf("Failed to create new engine : %v\n", err))
		}
	case "postgres":
		cnnstr := fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s",
			user, pwd, host, port, name, ssl)
		orm, err = xorm.NewEngine("postgres", cnnstr)
	default:
		beego.Debug(fmt.Sprintf("Unknown db type: %s\n", dbtype))
		return fmt.Errorf("Unknown db type: %s\n", dbtype)
	}

	if err != nil {
		beego.Debug(fmt.Sprintf("models.init(failed to connect database): %v\n", err))
		return fmt.Errorf("models.init(failed to connect database): %v\n", err)
	}

	// orm.ShowSQL = true
	// orm.ShowInfo = true
	// orm.ShowDebug = true
	// orm.ShowWarn = true
	orm.ShowErr = true
	fmt.Println("success!")
	return orm.Sync(tables...)
}
示例#5
0
文件: lasting.go 项目: aiwuTech/goAcq
func xConnDb() (*xorm.Engine, error) {

	switch DbType {
	case "sqlite":
		return xorm.NewEngine("sqlite3", filepath.Join(os.Getenv("GOPATH"), "src", "goAcq", "data", fmt.Sprintf("%s.db", DbName)))
	case "mysql":
		return xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%v)/%s?charset=%v", DbUser, DbPwd, DbHost, DbName, DbCharSet))
	case "pgsql":
		return xorm.NewEngine("postgres", fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", DbUser, DbPwd, DbName))
	}

	return nil, fmt.Errorf("UnSopported database type: %v", DbType)
}
示例#6
0
func InitDB() (err error) {
	utils.LoadConfig("../conf/app.conf")
	dbtype := utils.Cfg.MustValue("db", "dbtype")
	host := utils.Cfg.MustValue("db", "host")
	port := utils.Cfg.MustValue("db", "port")
	name := utils.Cfg.MustValue("db", "name")
	user := utils.Cfg.MustValue("db", "user")
	pwd := utils.Cfg.MustValue("db", "pwd")
	ssl := utils.Cfg.MustValue("db", "ssl")

	switch dbtype {
	case "mysql":
		// connstr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8",
		// 	user, pwd, host, port, name)
		connstr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8",
			user, pwd, host, port, name)
		fmt.Errorf(connstr)
		orm, err = xorm.NewEngine("mysql", connstr)
		if err != nil {
			beego.Debug(fmt.Sprintf("Failed to create new engine : %v\n", err))
		}
	case "postgres":
		cnnstr := fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s",
			user, pwd, host, port, name, ssl)
		orm, err = xorm.NewEngine("postgres", cnnstr)
	default:
		beego.Debug(fmt.Sprintf("Unknown db type: %s\n", dbtype))
		return fmt.Errorf("Unknown db type: %s\n", dbtype)
	}

	if err != nil {
		beego.Debug(fmt.Sprintf("models.init(failed to connect database): %v\n", err))
		return fmt.Errorf("models.init(failed to connect database): %v\n", err)
	}

	// orm.ShowSQL = true
	// orm.ShowInfo = true
	// orm.ShowDebug = true
	// orm.ShowWarn = true
	orm.ShowErr = true

	orm.SetMapper(core.SameMapper{})

	fmt.Println("success!")
	// return orm.Sync(tables...)
	err = orm.Sync(new(Test), new(PkgFunc))
	if err != nil {
		fmt.Println("Failed to Sync()!")
	}
	return
}
示例#7
0
func ExampleRegisterStandardDatabases() {
	engine1, _ = xorm.NewEngine("mysql", "root:@/example_user?charset=utf8")
	engine2, _ = xorm.NewEngine("mysql", "root:@/example_user?charset=utf8")
	engine3, _ = xorm.NewEngine("mysql", "root:@/example_foobar?charset=utf8")
	engine4, _ = xorm.NewEngine("mysql", "root:@/example_other?charset=utf8")

	w = wizard.NewWizard()
	stndardCluster := w.CreateCluster(User{}, engine1) // engine is master database used for table of User{}
	stndardCluster.RegisterSlave(engine2)              // add slave

	_ = w.CreateCluster("foobar", engine3) // engine3 is master database used for table of foobar

	stndardCluster = wizard.NewCluster(engine4)
	w.SetDefault(stndardCluster) // engine4 is master database used for all the other tables
}
示例#8
0
/**
**	初始化数据库连接
**/
func initDb() error {
	userName, err := util.GetValue("db", "userName")
	if err != nil {
		log.Fatalf("get value of userName from conf, %v", err)
		return err
	}
	pass, err := util.GetValue("db", "dbpass")
	if err != nil {
		log.Fatalf("get value of dbpass from conf, %v", err)
		return err
	}

	dbhost, err := util.GetValue("db", "dbhost")
	if err != nil {
		log.Fatalf("get value of dbhost from conf, %v", err)
		return err
	}
	dbport, err := util.GetValue("db", "dbport")
	if err != nil {
		log.Fatalf("get value of dbport from conf, %v", err)
		return err
	}
	dbname, err := util.GetValue("db", "dbname")
	if err != nil {
		log.Fatalf("get value of dbname from conf, %v", err)
		return err
	}

	dsn := []string{userName, ":", pass, "@tcp(", dbhost, ":", dbport, ")/", dbname}
	dsnStr := strings.Join(dsn, "")
	engine, err = xorm.NewEngine("mysql", dsnStr)
	return err
}
func init() {
	// 创建 ORM 引擎与数据库
	var err error
	x, err = xorm.NewEngine("sqlite3", "./bank.db")
	if err != nil {
		log.Fatalf("Fail to create engine: %v\n", err)
	}

	// 同步结构体与数据表
	if err = x.Sync(new(Account)); err != nil {
		log.Fatalf("Fail to sync database: %v\n", err)
	}

	// 记录日志
	f, err := os.Create("sql.log")
	if err != nil {
		log.Fatalf("Fail to create log file: %v\n", err)
		return
	}
	x.Logger = xorm.NewSimpleLogger(f)
	x.ShowSQL = true

	// 设置默认 LRU 缓存
	cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
	x.SetDefaultCacher(cacher)
}
示例#10
0
//初始化数据库
func (api *Api) InitDB(database string) {
	var err error
	conf, err := ConfigFromFile(configPath)
	if err != nil {
		panic(err.Error())
	}

	dbConf := conf.DataBase
	sqlUrl := fmt.Sprintf(dbConf.URL, dbConf.User, dbConf.Password, dbConf.Host, dbConf.Port, database)
	api.DB, err = xorm.NewEngine("mysql", sqlUrl)
	if err != nil {
		log.Fatalf("Got error when connect database, the error is '%v'", err)
	}
	api.DB.ShowSQL = true
	api.DB.ShowDebug = true
	api.DB.ShowErr = true
	api.DB.SetMaxIdleConns(dbConf.MaxIdleConnections)
	api.DB.SetMaxOpenConns(dbConf.MaxOpenConnections)

	//记录到日志文件中.
	//	f, err := os.Create("sql.log")
	//	if err != nil {
	//		println(err.Error())
	//		return
	//	}
	//	defer f.Close()
	//	api.DB.Logger = xorm.NewSimpleLogger(f)

}
示例#11
0
func getEngine() (*xorm.Engine, error) {
	cnnstr := ""
	switch DbCfg.Type {
	case "mysql":
		if DbCfg.Host[0] == '/' { // looks like a unix socket
			cnnstr = fmt.Sprintf("%s:%s@unix(%s)/%s?charset=utf8&parseTime=true",
				DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name)
		} else {
			cnnstr = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=true",
				DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name)
		}
	case "postgres":
		var host, port = "127.0.0.1", "5432"
		fields := strings.Split(DbCfg.Host, ":")
		if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
			host = fields[0]
		}
		if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
			port = fields[1]
		}
		cnnstr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=%s",
			url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, DbCfg.SSLMode)
	case "sqlite3":
		if !EnableSQLite3 {
			return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
		}
		if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
			return nil, fmt.Errorf("Fail to create directories: %v", err)
		}
		cnnstr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
	default:
		return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
	}
	return xorm.NewEngine(DbCfg.Type, cnnstr)
}
示例#12
0
// NewXormDBAppender create new db appender
func NewXormDBAppender(driver, spec, table string) (*XormDBAppender, error) {
	if table == "" {
		table = "common_wlog"
	}

	wlog.DB_LOG_TABLE = table

	m := &XormDBAppender{}

	e, err := xorm.NewEngine(driver, spec)
	if err != nil {
		return nil, err
	}

	// config Engine
	e.SetTableMapper(core.SnakeMapper{})
	e.SetColumnMapper(core.SameMapper{})

	// Sync Table
	e.Sync(wlog.LogTable{})

	m.Xorm = e

	m.BaseAppender = wlog.NewBaseAppender("db")

	return m, nil
}
示例#13
0
文件: simple.go 项目: tempbottle/xweb
func init() {
	var err error
	engine, err = xorm.NewEngine("sqlite3", "./data.db")
	if err != nil {
		fmt.Println(err)
		return
	}
	engine.ShowSQL = true
	err = engine.CreateTables(su)
	if err != nil {
		fmt.Println(err)
	} else {
		cnt, err := engine.Count(su)
		if err != nil {
			fmt.Println(err)
		} else if cnt == 0 {
			user := User{1, "admin", "123"}
			_, err := engine.Insert(&user)
			if err != nil {
				fmt.Println(err)
			} else {
				fmt.Println("Init db successfully!")
			}
		}
	}
}
示例#14
0
文件: conversion.go 项目: CowLeo/xorm
func main() {
	f := "conversion.db"
	os.Remove(f)

	Orm, err := xorm.NewEngine("sqlite3", f)
	if err != nil {
		fmt.Println(err)
		return
	}
	Orm.ShowSQL(true)
	err = Orm.CreateTables(&User{})
	if err != nil {
		fmt.Println(err)
		return
	}

	_, err = Orm.Insert(&User{1, "xlw", Registed})
	if err != nil {
		fmt.Println(err)
		return
	}

	users := make([]User, 0)
	err = Orm.Find(&users)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(users)
}
示例#15
0
// DB is used to make connection to datbase . You can pass database type and its access information like
// path to database or database name database user and database connection password .
func DB() martini.Handler {

	/*
	 * If you plan to use sqllite then make the following changes in config.ini
	 * DbDriver	= "sqlite3"
	 * DbSource	= "test.db"
	 *
	 * and import the sqllite driver
	 * _ "github.com/mattn/go-sqlite3"
	 *
	 */

	engine, err := xorm.NewEngine(conf.Setting.DbDriver, conf.Setting.DbSource)
	if err != nil {
		panic(err)
	}

	//engine.ShowSQL = true
	engine.Sync(
		&models.TestTable{},
	)

	return func(c martini.Context) {
		c.Map(engine)
		c.Next()
	}
}
func initDB(config EnvConfig) {
	var err error
	mysqlserver := fmt.Sprintf("%v:%v@%v/%v?charset=utf8&parseTime=true", config.DB.User, config.DB.Password, config.DB.Server, config.DB.Dbname)
	x, err = xorm.NewEngine("mysql", mysqlserver)
	if err != nil {
		glog.V(1).Infof("Connect DataBase Fail:%v", err.Error())
	}

	x.ShowSQL = true //打印SQL语句

	//创建表
	err = x.Sync2(new(Customer))
	if err != nil {
		glog.V(1).Infof("Sync DataBase Fail:%v", err.Error())
	}

	err = x.Sync2(new(Goods))
	if err != nil {
		glog.V(1).Infof("Sync DataBase Fail:%v", err.Error())
	}

	err = x.Sync2(new(Order))
	if err != nil {
		glog.V(1).Infof("Sync DataBase Fail:%v", err.Error())
	}
}
示例#17
0
文件: myinit.go 项目: ryancsq/test
func initDb() {
	var err error
	Engine, err = xorm.NewEngine("mysql", mysql_dsn)

	if err != nil {
		panic(err.Error()) // proper error handling instead of panic in your app
	}

	tbMapper := core.NewPrefixMapper(core.SnakeMapper{}, "pk_")
	Engine.SetTableMapper(tbMapper)

	Engine.ShowSQL = true   //则会在控制台打印出生成的SQL语句;
	Engine.ShowDebug = true //则会在控制台打印调试信息;
	Engine.ShowErr = true   //则会在控制台打印错误信息;
	Engine.ShowWarn = true  //则会在控制台打印警告信息;

	f, err := os.Create("sql.log")
	if err != nil {
		println("error:")
		println(err.Error())
		return
	}
	defer f.Close()
	Engine.Logger = xorm.NewSimpleLogger(f)
	//	fmt.Println(Engine)
}
示例#18
0
func ExampleRegisterShardedDatabase() {
	engine1, _ = xorm.NewEngine("mysql", "root:@/example_user_a?charset=utf8")
	engine2, _ = xorm.NewEngine("mysql", "root:@/example_user_a?charset=utf8")
	engine3, _ = xorm.NewEngine("mysql", "root:@/example_user_b?charset=utf8")
	engine4, _ = xorm.NewEngine("mysql", "root:@/example_user_b?charset=utf8")

	w = wizard.NewWizard()
	shardClusters := w.CreateShardCluster(&User{}, 997) // create shard clusters for User{} with slotsize 997
	standardClusterA := wizard.NewCluster(engine1)
	standardClusterA.RegisterSlave(engine2)
	shardClusters.RegisterShard(0, 500, standardClusterA)

	standardClusterB := wizard.NewCluster(engine3)
	standardClusterB.RegisterSlave(engine4)
	shardClusters.RegisterShard(501, 996, standardClusterB)
}
示例#19
0
func TestMysqlGonicMapper(t *testing.T) {
	err := mysqlDdlImport()
	if err != nil {
		t.Error(err)
		return
	}

	engine, err := xorm.NewEngine("mysql", "root:@/xorm_test1?charset=utf8")
	if err != nil {
		t.Error(err)
		return
	}
	defer engine.Close()

	engine.ShowSQL = ShowTestSql
	engine.ShowErr = ShowTestSql
	engine.ShowWarn = ShowTestSql
	engine.ShowDebug = ShowTestSql
	engine.SetMapper(core.GonicMapper{})

	BaseTestAll(engine, t)
	//BaseTestAllSameMapper(engine, t)
	BaseTestAll2(engine, t)
	BaseTestAll3(engine, t)
}
示例#20
0
func TestMysqlWithCacheSameMapper(t *testing.T) {
	err := mysqlDdlImport()
	if err != nil {
		t.Error(err)
		return
	}

	engine, err := xorm.NewEngine("mysql", "root:@/xorm_test3?charset=utf8")
	if err != nil {
		t.Error(err)
		return
	}
	defer engine.Close()

	engine.SetMapper(core.SameMapper{})
	engine.SetDefaultCacher(NewCacher())
	engine.ShowSQL = ShowTestSql
	engine.ShowErr = ShowTestSql
	engine.ShowWarn = ShowTestSql
	engine.ShowDebug = ShowTestSql

	BaseTestAll(engine, t)
	BaseTestAllSameMapper(engine, t)
	BaseTestAll2(engine, t)
}
示例#21
0
func init() {
	var err error
	X, err = xorm.NewEngine("mssql", "server=.;database=goodsmanage;user id=sa;password=yiche2014")
	fmt.Println("-------11111")
	if err != nil {
		log.Fatalf("failt to carete engine")
	}
	fmt.Println("-------11111")
	X.SetMapper(core.SameMapper{})
	//用户表
	if err = X.Sync2(new(Tuser)); err != nil {
		log.Fatalf("failt Tuser to sync", err.Error())
	}
	//菜单表
	if err = X.Sync2(new(TMenus)); err != nil {
		log.Fatalf("failt TMenus to sync", err.Error())
	}
	//角色表
	if err = X.Sync2(new(TRoles)); err != nil {
		log.Fatalf("failt TRoles to sync", err.Error())
	}
	//初始管理员
	// var tuser = new(Tuser).Init()
	// var d = tuser.GetUser("admin")
	// if d == false {
	// 	_, _ = X.Exec("insert into [Tuser]([uname],password)values('admin','admin')")
	// }
	var tuser = new(Tuser).Init()
	if !tuser.Get(1) {
		_, _ = X.Exec("insert into [Tuser]([uname],password)values('admin','admin')")
	}

}
示例#22
0
文件: source.go 项目: sillydong/cmd
func runSource(cmd *Command, args []string) {
	if len(args) != 2 {
		fmt.Println("params error, please see xorm help source")
		return
	}

	var err error
	engine, err = xorm.NewEngine(args[0], args[1])
	if err != nil {
		fmt.Println(err)
		return
	}

	engine.ShowSQL, engine.ShowDebug = false, false
	engine.ShowErr, engine.ShowWarn = false, false

	err = engine.Ping()
	if err != nil {
		fmt.Println(err)
		return
	}

	_, err = engine.Import(os.Stdin)
	if err.Error() == "not an error" {
		err = nil
	}
	if err != nil {
		fmt.Println(err)
		return
	}
}
示例#23
0
文件: dump.go 项目: chrislonng/cmd
func runDump(cmd *Command, args []string) {
	if len(args) != 2 {
		fmt.Println("params error, please see xorm help dump")
		return
	}

	var err error
	engine, err = xorm.NewEngine(args[0], args[1])
	if err != nil {
		fmt.Println(err)
		return
	}

	engine.ShowSQL(false)
	engine.Logger().SetLevel(core.LOG_UNKNOWN)

	err = engine.Ping()
	if err != nil {
		fmt.Println(err)
		return
	}

	err = engine.DumpAll(os.Stdout)
	if err != nil {
		fmt.Println(err)
		return
	}
}
示例#24
0
文件: sql.go 项目: kyugao/gametcp_ex
func init() {

	c, err := goconfig.LoadConfigFile("conf/conf.ini")
	if err != nil {
		panic(err)
	}

	driver, err := c.GetValue("Database", "driver")
	if err != nil {
		panic(err)
	}
	dsn, err := c.GetValue("Database", "dsn")

	if err != nil {
		panic(err)
	}

	DataBase, err = xorm.NewEngine(driver, dsn)
	if err != nil {
		panic(err)
	}

	err = DataBase.Ping()
	if err != nil {
		panic(err)
	}
}
示例#25
0
文件: models.go 项目: wxiangbo/gogs
func getEngine() (*xorm.Engine, error) {
	cnnstr := ""
	switch DbCfg.Type {
	case "mysql":
		if DbCfg.Host[0] == '/' { // looks like a unix socket
			cnnstr = fmt.Sprintf("%s:%s@unix(%s)/%s?charset=utf8",
				DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name)
		} else {
			cnnstr = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
				DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name)
		}
	case "postgres":
		var host, port = "127.0.0.1", "5432"
		fields := strings.Split(DbCfg.Host, ":")
		if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
			host = fields[0]
		}
		if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
			port = fields[1]
		}
		cnnstr = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s",
			DbCfg.User, DbCfg.Passwd, host, port, DbCfg.Name, DbCfg.SSLMode)
	case "sqlite3":
		if !EnableSQLite3 {
			return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
		}
		os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
		cnnstr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
	default:
		return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
	}
	return xorm.NewEngine(DbCfg.Type, cnnstr)
}
示例#26
0
func main() {
	f := "singleMapping.db"
	os.Remove(f)

	Orm, err := xorm.NewEngine("sqlite3", f)
	if err != nil {
		fmt.Println(err)
		return
	}
	Orm.ShowSQL = true
	err = Orm.CreateTables(&User{}, &LoginInfo{})
	if err != nil {
		fmt.Println(err)
		return
	}

	_, err = Orm.Insert(&User{1, "xlw"}, &LoginInfo{1, "127.0.0.1", 1, "", 23})
	if err != nil {
		fmt.Println(err)
		return
	}

	info := LoginInfo{}
	_, err = Orm.Id(1).Get(&info)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(info)
}
示例#27
0
文件: cao.go 项目: hefju/DbSync
//var engine *xorm.Engine
func Update0508() {
	var err error
	engine, err = xorm.NewEngine("sqlite3", "./test.db")
	engine.SetMapper(core.SameMapper{})
	if err != nil {
		fmt.Println(err)
	}
	cs := make([]Coordinate, 0)
	err = engine.Where("FormName='Frm05_8'").Find(&cs)
	if err != nil {
		fmt.Println(err)
	}

	ps := make([]PageProfile, 0)
	err = engine.Where("FormName='Frm05_8'").Find(&ps)
	if err != nil {
		fmt.Println(err)
	}

	for _, coor := range cs {
		cname := coor.CoordinateName
		for _, pro := range ps {
			pname := pro.ItemName_CN + pro.Display_CN
			if cname == pname {
				coor.CustomID = pro.CustomID
				_, err := engine.Id(coor.ID).Cols("CustomID").Update(&coor)
				if err != nil {
					fmt.Println(err)
				}
			}
		}
	}

}
示例#28
0
func getEngine() (*xorm.Engine, error) {
	LoadConfig()

	cnnstr := ""
	switch DbCfg.Type {
	case "mysql":
		cnnstr = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
			DbCfg.User, DbCfg.Pwd, DbCfg.Host, DbCfg.Name)
	case "postgres":
		var host, port = "127.0.0.1", "5432"
		fields := strings.Split(DbCfg.Host, ":")
		if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
			host = fields[0]
		}
		if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
			port = fields[1]
		}
		cnnstr = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s",
			DbCfg.User, DbCfg.Pwd, host, port, DbCfg.Name, DbCfg.SslMode)
	case "sqlite3":
		if !filepath.IsAbs(DbCfg.Path) {
			DbCfg.Path = filepath.Join(setting.DataPath, DbCfg.Path)
		}
		os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
		cnnstr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc&_loc=Local"
	default:
		return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
	}

	log.Info("Database: %v", DbCfg.Type)

	return xorm.NewEngine(DbCfg.Type, cnnstr)
}
示例#29
0
文件: driver.go 项目: mabetle/mdb
// NewXorm
func NewXorm(conf *dbconf.DBConf) (*mdb.Xorm, error) {
	logger.Tracef("Create new mdb.Xorm, DB: %s ", conf.Database)

	// check args
	if conf == nil {
		return nil, fmt.Errorf("DBConf is nil")
	}

	engine, err := xorm.NewEngine("mysql", conf.GetMySqlConnURL())
	if logger.CheckError(err) {
		return nil, err
	}

	// set engine default config
	//engine.ShowSQL = false
	//engine.ShowDebug = false
	//engine.ShowErr = true
	//engine.ShowWarn = false

	engine.SetTableMapper(core.SnakeMapper{})

	//engine.SetColumnMapper(core.SnakeMapper{})
	engine.SetColumnMapper(core.SameMapper{})

	return mdb.NewXorm(engine), nil
}
示例#30
-2
func (s *Sprint) Run() error {
	var err error

	dsn, _ := pq.ParseURL(os.Getenv("DATABASE_URL"))
	db, err := xorm.NewEngine("postgres", dsn)
	if err != nil {
		return err
	}

	err = db.Sync(Project{})
	if err != nil {
		return err
	}

	s.Db = db

	s.Validator = validator.New(&validator.Config{TagName: "validate"})

	port := os.Getenv("PORT")

	r := gin.Default()

	r.GET("/api/projects", s.GetProjects)
	r.GET("/api/projects/:id", s.GetProjectsOne)
	r.POST("/api/projects", s.CreateProjects)
	r.DELETE("/api/projects/:id", s.DeleteProjects)

	r.Run(":" + port)

	return nil
}