Skip to content
This repository has been archived by the owner on May 24, 2020. It is now read-only.

Latest commit

 

History

History
96 lines (66 loc) · 2.67 KB

1.engine.md

File metadata and controls

96 lines (66 loc) · 2.67 KB

Create Engine

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"
    "github.com/go-xorm/xorm"
)

var engine *xorm.Engine

func main() {
    var err error
    engine, err = xorm.NewEngine("mysql", "root:123@/test?charset=utf8")
}

or

import (
    _ "github.com/mattn/go-sqlite3"
    "github.com/go-xorm/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 7 drivers now:

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(core.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(xorm.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 := xorm.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+.