Create Engine
Create Engine
When using xorm, you can create one or more ORM engines in one application. XORM supports two kinds of engines, Engine
and EngineGroup
. An engine could operate one database and an engine group could handle Master/Slave situations. Both kinds of engines have similar APIs, so that you can easily change from one to another. We also provide an EngineInterface
to do that.
One app could create one or more engines. One engine could handle one database. You can invoke xorm.NewEngine
to do that. For example:
import (
_ "github.com/go-sql-driver/mysql"
"xorm.io/xorm"
)
var engine *xorm.Engine
func main() {
var err error
engine, err = xorm.NewEngine("mysql", "root:[email protected]/test?charset=utf8")
}
or
import (
_ "github.com/mattn/go-sqlite3"
"xorm.io/xorm"
)
var engines []*xorm.Engine
func main() {
for i:=0; i < 10; i++ {
engine, err := xorm.NewEngine("sqlite3", fmt.Sprintf("./test%d.db", i))
engines = append(engines, engine)
}
}
You can create many engines for different databases. Generally, you just need to create only one engine. Engine supports run on go routines.
When you want to manually close the engine, call engine.Close
. Generally, we don’t need to do this, because engine will be closed automatically when application exits.
xorm supports drivers as below:
MsSql
Oracle
- github.com/mattn/go-oci8 (experiment)
NewEngine’s parameters are the same as sql.Open
. So you should read the driver’s document for parameter’s usage.
After engine is created, you can do some settings.
Logs
engine.ShowSQL(true)
, Shows SQL statement on standard output or your io.Writer;engine.Logger().SetLevel(log.LOG_DEBUG)
, Shows debug and other infomations;
If you want to record infomations with another method: use engine.SetLogger()
as io.Writer
:
f, err := os.Create("sql.log")
if err != nil {
println(err.Error())
return
}
engine.SetLogger(log.NewSimpleLogger(f))
Logs also support recording to syslog, for example:
logWriter, err := syslog.New(syslog.LOG_DEBUG, "rest-xorm-example")
if err != nil {
log.Fatalf("Fail to create xorm system logger: %v\n", err)
}
logger := log.NewSimpleLogger(logWriter)
logger.ShowSQL(true)
engine.SetLogger(logger)
Connections pool
Engine provides DB connections pool settings.
- Use
engine.SetMaxIdleConns()
to set idle connections. - Use
engine.SetMaxOpenConns()
to set Max connections. This methods support only Go 1.2+. - Use
engine.SetConnMaxLifetime()
to set Max life time. This methods support only Go 1.6+.