使用 database/sql 和 使用 gorm 的区别

参考解析

题目来源:360

答案:

Go操作Mysql数据库,一般有两种方式:

  • 通过 database/sql 接口
  • 通过 GORM 对象关系映射

使用 database/sql 接口
Go没有内置驱动支持任何数据库,用户可以基于驱动接口开发相应数据库的驱动。使用该直接将在代码里硬编码sql语句。

示例代码:

  1. // 创建表
  2. func CreateTable(DB *sql.DB) {
  3. sql := `CREATE TABLE IF NOT EXISTS users(
  4. id INT(4) PRIMARY KEY AUTO_INCREMENT NOT NULL,
  5. username VARCHAR(64),
  6. password VARCHAR(64),
  7. status INT(4),
  8. createtime INT(10)
  9. ); `
  10. if _, err := DB.Exec(sql); err != nil {
  11. fmt.Println("create table failed:", err)
  12. return
  13. }
  14. fmt.Println("create table successd")
  15. }

使用 GORM
GORM(Object Relation Mapping),即Go语言中的对象关系映射,实际上就是对数据库的操作进行封装,对上层开发人员屏蔽数据操作的细节,开发人员看到的就是一个个对象,大大简化了开发工作,提高了生产效率。可以通过结合 Gin 等服务端框架使用可以开发出丰富的Rest API。

示例代码:

  1. type User struct {
  2. Id int `gorm:"size:11;primary_key;AUTO_INCREMENT;not null" json:"id"`
  3. Age int `gorm:"size:11;DEFAULT NULL" json:"age"`
  4. Name string `gorm:"size:255;DEFAULT NULL" json:"name"`
  5. //gorm后添加约束,json后为对应mysql里的字段
  6. }
  7. func main() {
  8. DB, err := gorm.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8")
  9. if err != nil {
  10. fmt.Println("failed to connect database:", err)
  11. return
  12. }else{
  13. fmt.Println("connect database success")
  14. // 创建表方法封装
  15. DB.AutoMigrate(&User{}) //通过 User 对象结构创建表
  16. fmt.Println("create table success")
  17. }
  18. defer DB.Close()
  19. }

参考资料

Mysql – database/sql / GORM
https://blog.csdn.net/ayqy42602/article/details/107774045