GORM 官网反对的数据库类型有:MySQL,PostgreSQL,SQlite,SQL Server
MYSQL
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main() {
// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
}
PostgreSQL
import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
dsn := "host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
#### SQLite
import (
"gorm.io/driver/sqlite" // Sqlite driver based on GGO
// "github.com/glebarez/sqlite"
// Pure go SQLite driver, checkout https://github.com/glebarez/sqlite for details
"gorm.io/gorm"
)
// github.com/mattn/go-sqlite3
db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})
SQL Server
import (
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
)
// github.com/denisenkom/go-mssqldb
dsn := "sqlserver://gorm:LoremIpsum86@localhost:9930?database=gorm"
db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{})
连接池
GORM 应用 database/sql 保护连接池
sqlDB, err := db.DB()
// SetMaxIdleConns 设置闲暇连接池中连贯的最大数量
sqlDB.SetMaxIdleConns(10)
// SetMaxOpenConns 设置关上数据库连贯的最大数量。sqlDB.SetMaxOpenConns(100)
// SetConnMaxLifetime 设置了连贯可复用的最大工夫。sqlDB.SetConnMaxLifetime(time.Hour)
Create
package main
import (
"database/sql"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"time"
)
type Userinfo struct {
Id uint
Name string
Gender string
Hobby string
}
type UserTest struct {
ID uint
Name string
Email *string
Age uint8
Birthday *time.Time
MemberNumber sql.NullString
ActivatedAt sql.NullTime
CreatedAt time.Time
UpdatedAt time.Time
}
func main() {
// 连贯数据库
dsn := "root:xixxxxxu@tcp(10.xx.18x.1x:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
//// 主动迁徙
//db.AutoMigrate(&Userinfo{})
//u1 := Userinfo{Id: 1, Name: "张三", Gender: "男", Hobby: "学习"}
//db.Create(&u1) // 创立
//create table and inster
db.AutoMigrate(&UserTest{})
britime := time.Now()
user := UserTest{Name: "Sean", Age: 17, Birthday: &britime}
result := db.Create(&user)
//user.ID // 返回插入数据的主键
//result.Error // 返回 error
//result.RowsAffected // 返回插入记录的条数
fmt.Println(user.ID, result.Error, result.RowsAffected)
}
Query
// 获取第一条记录(主键升序)db.First(&user)
// SELECT * FROM users ORDER BY id LIMIT 1;
// 获取一条记录,没有指定排序字段
db.Take(&user)
// SELECT * FROM users LIMIT 1;
// 获取最初一条记录(主键降序)db.Last(&user)
// SELECT * FROM users ORDER BY id DESC LIMIT 1;
result := db.First(&user)
result.RowsAffected // 返回找到的记录数
result.Error // returns error or nil
// 查看 ErrRecordNotFound 谬误
errors.Is(result.Error, gorm.ErrRecordNotFound)
func main() {
// 连贯数据库
dsn := "root:xixxxxxu@tcp(1xxxxxxx:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
//// 主动迁徙
//db.AutoMigrate(&Userinfo{})
//u1 := Userinfo{Id: 1, Name: "张三", Gender: "男", Hobby: "学习"}
//db.Create(&u1) // 创立
////create table and inster
//db.AutoMigrate(&UserTest{})
//
//britime := time.Now()
//user := UserTest{Name: "Sean", Age: 17, Birthday: &britime}
//result := db.Create(&user)
////user.ID // 返回插入数据的主键
////result.Error // 返回 error
////result.RowsAffected // 返回插入记录的条数
//fmt.Println(user.ID, result.Error, result.RowsAffected)
//Query
var user_test UserTest
//var users []UserTest
result := db.First(&user_test, "id = ?", 1)
// SELECT * FROM users WHERE id = 1
db.Model(UserTest{}).First(&user_test)
fmt.Println(result.RowsAffected, user_test)
}
redis
package main
import (
"fmt"
"github.com/go-redis/redis"
)
func ConnRedis() {
rd := redis.NewClient(&redis.Options{
Addr: "10.2x.1xx.1xx:6379", // url
Password: "XixxxxU",
DB:0, // 0 号数据库
})
result, err := rd.Ping().Result()
if err != nil {fmt.Println("ping err :",err)
return
}
fmt.Println(result)
}
var rd *redis.Client= redis.NewClient(&redis.Options{
Addr: "10.23.x8.xx:6379", // url
Password: "XxxxxU",
DB:7, // 数据库
})
// string 操作
func SetAndGet() {
// set 操作:第三个参数是过期工夫,如果是 0 示意不会过期。defer rd.Close() // 记得敞开连贯
err := rd.Set("prüfung", "hallo kugou",0).Err()
if err != nil {fmt.Println("set err :",err)
return
}
// get 操作
val,err := rd.Get("prüfung").Result()
if err != nil {fmt.Println("get err :",err)
return
}
fmt.Println("k1 ==",val)
}
// 申明一个全局的 rdb 变量
var rdb *redis.Client
// 初始化连贯
func initClient() (err error) {
rdb = redis.NewClient(&redis.Options{
Addr: "10.23.1x.1x:6379",
Password: "XixxxxxU", // no password set
DB: 7, // use default DB
})
_, err = rdb.Ping().Result()
if err != nil {return err}
return nil
}
//initClientS 哨兵模式
func initClientS()(err error){
rdb := redis.NewFailoverClient(&redis.FailoverOptions{
MasterName: "master",
SentinelAddrs: []string{"x.x.x.x:26379", "xx.xx.xx.xx:26379", "xxx.xxx.xxx.xxx:26379"},
})
_, err = rdb.Ping().Result()
if err != nil {return err}
return nil
}
// cluster
func initClientC()(err error){
rdb := redis.NewClusterClient(&redis.ClusterOptions{Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},
})
_, err = rdb.Ping().Result()
if err != nil {return err}
return nil
}
func redisExample() {err := rdb.Set("score", 100, 0).Err()
if err != nil {fmt.Printf("set score failed, err:%v\n", err)
return
}
val, err := rdb.Get("score").Result()
if err != nil {fmt.Printf("get score failed, err:%v\n", err)
return
}
fmt.Println("score", val)
val2, err := rdb.Get("name").Result()
if err == redis.Nil {fmt.Println("name does not exist")
} else if err != nil {fmt.Printf("get name failed, err:%v\n", err)
return
} else {fmt.Println("name", val2)
}
}
func main() {ConnRedis()
SetAndGet()}