TeamClass_MD/Go入门速成/Day2/Class3 Gorm的使用.md
2025-03-19 15:59:50 +08:00

31 lines
828 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Gorm的使用
## Gorm是什么
- GORM 是 Go 语言的 ORM 库,提供模型定义、关联管理、事务支持、查询构建、数据迁移、钩子回调等功能,支持主流数据库(如 MySQL/PostgreSQL/SQLite简化数据库操作。
## 如何使用Gorm
### 导入Gorm库
```go
import (
"gorm.io/driver/mysql"
)
```
### 基本操作
- 1、连接数据库
```go
const (
USERNAME = "root"
PASSWD = "oppofindx2"
DATABASENAME = "Class"
)
dsn := fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/%s?charset=utf8mb4&parseTime=True&loc=Local", USERNAME, PASSWD, DATABASENAME)
db := mysql.Open(dsn)
`````
- 2、数据库中表的定义
- 在Gorm中定义一张表使用的是结构体
```go
type User struct {
gorm.Model
Name string
Age int
}
```
- 自动迁移表结构(方便我们修改表,给表添加参数)