使用 database/sql 和 使用 gorm 的区别
参考解析
题目来源:360
答案:
Go操作Mysql数据库,一般有两种方式:
- 通过 database/sql 接口
- 通过 GORM 对象关系映射
使用 database/sql 接口
Go没有内置驱动支持任何数据库,用户可以基于驱动接口开发相应数据库的驱动。使用该直接将在代码里硬编码sql语句。
示例代码:
// 创建表
func CreateTable(DB *sql.DB) {
sql := `CREATE TABLE IF NOT EXISTS users(
id INT(4) PRIMARY KEY AUTO_INCREMENT NOT NULL,
username VARCHAR(64),
password VARCHAR(64),
status INT(4),
createtime INT(10)
); `
if _, err := DB.Exec(sql); err != nil {
fmt.Println("create table failed:", err)
return
}
fmt.Println("create table successd")
}
使用 GORM
GORM(Object Relation Mapping),即Go语言中的对象关系映射,实际上就是对数据库的操作进行封装,对上层开发人员屏蔽数据操作的细节,开发人员看到的就是一个个对象,大大简化了开发工作,提高了生产效率。可以通过结合 Gin 等服务端框架使用可以开发出丰富的Rest API。
示例代码:
type User struct {
Id int `gorm:"size:11;primary_key;AUTO_INCREMENT;not null" json:"id"`
Age int `gorm:"size:11;DEFAULT NULL" json:"age"`
Name string `gorm:"size:255;DEFAULT NULL" json:"name"`
//gorm后添加约束,json后为对应mysql里的字段
}
func main() {
DB, err := gorm.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8")
if err != nil {
fmt.Println("failed to connect database:", err)
return
}else{
fmt.Println("connect database success")
// 创建表方法封装
DB.AutoMigrate(&User{}) //通过 User 对象结构创建表
fmt.Println("create table success")
}
defer DB.Close()
}
参考资料
Mysql – database/sql / GORM
https://blog.csdn.net/ayqy42602/article/details/107774045