Register database

Beego ORM requires explicit registration of database information before it can be freely used。

And of course, never forget the anonymous introduction of the driver:

  1. import (
  2. _ "github.com/go-sql-driver/mysql"
  3. _ "github.com/lib/pq"
  4. _ "github.com/mattn/go-sqlite3"
  5. )

The above three, you can introduce one according to your needs.

Example:

  1. // args[0] Alias of the database, used to switch the database in ORM
  2. // args[1] driverName
  3. // args[2] DSN
  4. orm.RegisterDataBase("default", "mysql", "root:root@/orm_test?charset=utf8")
  5. // args[3](optional) max number of idle connections
  6. // args[4](optional) max number of connections (go >= 1.2)
  7. maxIdle := 30
  8. maxConn := 30
  9. orm.RegisterDataBase("default", "mysql", "root:root@/orm_test?charset=utf8", orm.MaxIdleConnections(maxIdle), orm.MaxOpenConnections(maxConn))

ORM requires a default database to be registered. And Beego’s ORM does not manage connections itself, but relies directly on the driver.

Configuration

Max number of connections

There are two ways to set the maximum number of connections, one way is to use the MaxOpenConnections option when registering the database:

  1. orm.RegisterDataBase("default", "mysql", "root:root@/orm_test?charset=utf8", orm.MaxOpenConnections(100))

It can also be modified after registration:

  1. orm.SetMaxOpenConns("default", 30)

Max number of idle connections

There are two ways to set the maximum number of idle connections, one way is to use the MaxIdleConnections option when registering the database:

  1. orm.RegisterDataBase("default", "mysql", "root:root@/orm_test?charset=utf8", orm.MaxIdleConnections(20))

Time zone

ORM uses time.Local as default time zone, and you can modify it by:

  1. // 设置为 UTC 时间
  2. orm.DefaultTimeLoc = time.UTC

ORM will get the time zone used by the database while doing RegisterDataBase, and then do the corresponding conversion when accessing the time.Time type to match the time system, so as to ensure that the time will not be wrong.

Notice:

  • Given the design of Sqlite3, accesses default to UTC time
  • When using the go-sql-driver driver, please pay attention to the configuration From a certain version, the driver uses UTC time by default instead of local time, so please specify the time zone parameter or access it all in UTC time: For example root:root@/orm_test?charset=utf8&loc=Asia%2FShanghai More details refer loc / parseTime

Driver

Most of the time, you only need to use the default ones for drivers that have:

  1. DRMySQL // mysql
  2. DRSqlite // sqlite
  3. DROracle // oracle
  4. DRPostgres // pgsql
  5. DRTiDB // TiDB

If you need to register a custom driver, you can use.

  1. // args[0] driverName
  2. // args[1] driver implementation
  3. // mysql / sqlite3 / postgres / tidb were registered automatically
  4. orm.RegisterDriver("mysql", yourDriver)