企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 1.安装gorm ~~~ go get github.com/jinzhu/gorm ~~~ ## 2.快速开始 ~~~ package main import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" ) func main() { db, err := gorm.Open("sqlite3", "test.db") if err != nil { panic("failed to connect database") } defer db.Close() ~~~ ## 3.gorm.Model gorm.Model包含基本字段,ID、CreatedAt、UpdatedAt、DeletedAt。 ~~~ package gorm import "time" type Model struct { ID uint `gorm:"primary_key"` CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time `sql:"index"` } ~~~ GORM默认使用ID作为主键名。如果定义的结构体中有ID字段,将被作为主键名;也可将其他字段设为主键。 ``` user_id `gorm:"primary_key"` ``` ## 4.连接数据库 导入对应的数据库驱动 ~~~ import _ "github.com/jinzhu/gorm/dialects/mysql" // import _ "github.com/jinzhu/gorm/dialects/postgres" // import _ "github.com/jinzhu/gorm/dialects/sqlite" // import _ "github.com/jinzhu/gorm/dialects/mssql" ~~~ **MySQL** ~~~ import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) func main() { db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local") defer db.Close() } ~~~ **PostgreSQL** ~~~ import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" ) func main() { db, err := gorm.Open("postgres", "host=myhost port=myport user=gorm dbname=gorm password=mypassword") defer db.Close() } ~~~ **Sqlite3** ~~~ import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" ) func main() { db, err := gorm.Open("sqlite3", "/tmp/gorm.db") defer db.Close() } ~~~ **SQL Server** ~~~ import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mssql" ) func main() { db, err := gorm.Open("mssql", "sqlserver://username:password@localhost:1433?database=dbname") defer db.Close() } ~~~