golang有没有orm可以根据代码定义表结构自动生成数据库表?
网友回复
gorm可以实现
1、安装
go get -u gorm.io/gorm go get -u gorm.io/driver/mysql
2、连接数据库
dsn := "username:passwd@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { fmt.Println(err) } fmt.Println(db)3、自动创建表
package main import ( "fmt" "gorm.io/driver/mysql" "gorm.io/gorm" ) type User struct { Id int64 `gorm:"primary_key" json:"id"` // 设置id为主键 Username string Password string } func main() { dsn := "root:123456@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { fmt.Println(err) } fmt.Println(db) db.AutoMigrate(User{}) // 自动创建表结构 }4、增删改查
package main import ( "fmt" "gorm.io/driver/mysql" "gorm.io/gorm" ) type User struct { Id int64 `gorm:"primary_key" json:"id"` Username string Password string } func main() { dsn := "root:123456@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { fmt.Println(err) } db.Create(&User{ Id: 1, Username: "test", Password: "123456", }) // 新增一条数据,相当于INSERT INTO `test_db`.`users` (`id`,`username`,`password`) VALUES (1, 'test', '123456'); db.Model(User{ Id: 1, }).Update("username", "test2") // 更新用户名为test2,相当于 update user set username="test2" where id = 1 db.Delete(&User{Id: 3}) // 删除id是1的用户,相当于delete from user where id = 3 db.Where("username = ?", "test3").Delete(&User{}) // 相当于delete from user where username = "test3" u := User{Id: 1} db.First(&u) fmt.Println(u) // 查询id是1的用户,只查一条 select * from user where id = 1 limit 1; users := []User{} db.Find(&users) fmt.Println(users) // 查询user表下的所有书籍, select * from user; }5、模型定义
type User struct { Id int64 `gorm:"primary_key" json:"id"` Name string ...
点击查看剩余70%