千家信息网

如何使用gorm语句

发表于:2026-11-03 作者:千家信息网编辑
千家信息网最后更新 2026年11月03日,本篇内容介绍了"如何使用gorm语句"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!gormSQL 拼
千家信息网最后更新 2026年11月03日如何使用gorm语句

本篇内容介绍了"如何使用gorm语句"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

gorm

  • SQL 拼写

  • SQL 执行

  • prometheus 监控

1.SQL 拼写

gorm/tree/master/callbacks包实现了CURD.

  • select

  • create

  • update

  • delete

  • transaction

type Statement struct {        Table                string        Model                interface{}        Selects              []string // selected columns        Preloads             map[string][]interface{}        Settings             sync.Map        ConnPool             ConnPool        Context              context.Context        SQL                  strings.Builder        Vars                 []interface{}    // ....}
  • SQL: 拼SQL的格式

  • Vars: sql格式中占位符对应的值.

select:

SELECT * FROM `sys_users` WHERE (username = ? AND password = ?) AND `sys_users`.`deleted_at` IS NULL ORDER BY `sys_users`.`id` LIMIT 1

2.SQL 执行

  • sql

  • params

  • result = cursor.execute(sql, params)

  • result 转为gorm中的Model对象.

ConnPool.ExecContext 定义返回值是sql.Rows 驱动层的数据.

import (        "context"        "database/sql")type ConnPool interface {        PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)        ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)        QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)        QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row}

gorm执行sql:

result, err := db.Statement.ConnPool.ExecContext(db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars...)// result 转为
  • err: sql执行是否出错

  • result: db server 返回的结果.

"如何使用gorm语句"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!

0