初始化Go学习项目

This commit is contained in:
liumangmang
2025-12-26 17:56:02 +08:00
commit 7f4527d501
90 changed files with 3436 additions and 0 deletions

47
go-gorm-demo/raw_sql.go Normal file
View File

@@ -0,0 +1,47 @@
package main
import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
//type User struct {
// ID uint `gorm:"primaryKey"`
// Name string `gorm:"size:100"`
// Email string `gorm:"size:100;unique"`
// Age int
// Active bool `gorm:"default:true"`
//}
func main() {
db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
db.AutoMigrate(&User{})
// 插入测试数据
db.Create(&User{Name: "Alice", Email: "alice@example.com", Age: 30})
db.Create(&User{Name: "Bob", Email: "bob@example.com", Age: 25})
// 1. 原生查询
var users []User
db.Raw("SELECT * FROM users WHERE age > ?", 20).Scan(&users)
fmt.Printf("Raw query result: %d users\n", len(users))
// 2. 原生更新
db.Exec("UPDATE users SET age = age + 1 WHERE name = ?", "Alice")
fmt.Println("Raw update executed")
// 3. 原生统计
var count int64
db.Raw("SELECT COUNT(*) FROM users").Scan(&count)
fmt.Printf("Total users: %d\n", count)
// 4. 查询单行
var result struct {
Name string
Age int
}
db.Raw("SELECT name, age FROM users WHERE id = ?", 1).Scan(&result)
fmt.Printf("User: %s (age=%d)\n", result.Name, result.Age)
}