This is a creation in Article, where the information may have evolved or changed.
Object Relational Mapping
, or ORM, is used to convert data between non-type systems in an object-oriented programming language. In effect, it actually creates a "virtual object database" that can be used in a programming language.
beego
is a fast-developing HTTP framework for the Go app developed by the great God, a restful framework.
Record how to configure the database in Beego as an MySql
example
Database selection
Currently, the Beego ORM supports three types of databases:
1.Sqlite2.PostgreSql3.MySql
If you want to use the database, you must add the corresponding drive
(go language for the database engine) into the import:
import ( _ "github.com/go-sql-driver/mysql" _ "github.com/lib/pq" _ "github.com/mattn/go-sqlite3")
Database Registration
Orm. Registerdriver ("MySQL", Orm.) Drmysql)
The meaning of this sentence is to register the MySQL database, of course, we want to import in the ORM package for:
import( "github.com/astaxie/beego/orm")
The first parameter is drivername, and the second parameter is the type of ORM for three databases:
orm.DRMySQLorm.DRSqliteorm.DRPostgres
Database connection
Beego must register an alias for default
the database, as the default usage.
Orm. RegisterDatabase ("Default", "MySQL", "Test:123456@/test?charset=utf8", 30,30)
The first parameter is the alias of the database that is used to switch the database.
The second one is driverName
, registered at Registerdriver.
The third is the database connection string: test:123456@/test?charset=utf8
relative to用户名:密码@数据库地址+名称?字符集
The fourth parameter is the equivalent of:
Orm. Setmaxidleconns ("Default", 30)
Sets the maximum idle connection for the database.
The fifth parameter is the equivalent of:
Orm. Setmaxopenconns ("Default", 30)
Sets the maximum database connection for the database.
The fourth and fifth parameters can also be passed without a value, using the database default values:
Time
Once I encountered a project where the time zone of the database was inconsistent with the ORM time zone setting, resulting in a much more complex development later. Beego will be used DefaultTimeLoc
to ensure that the time is not wrong
Beego uses the time.Local
local time zone by default, which can be used to automatically create time and remove time transitions from the data.
Orm. Defaulttimeloc = time. Utc
You can set the default time zone.
When the registerdatabase is performed, the time zone used by the database is taken, the response is converted, and the time is matched to ensure that there is no error.
The use of the process can be considered to unix时间戳
represent the time field, the advantage is good sorting, time zone conversion is also relatively easy.