// different databases generate different SQL stmt := db.Find(&user, 1).Statement stmt.SQL.String() //=> SELECT * FROM `users` WHERE `id` = $1 // PostgreSQL stmt.SQL.String() //=> SELECT * FROM `users` WHERE `id` = ? // MySQL stmt.Vars //=> []interface{}{1}
要生成最终的 SQL,您可以使用以下代码
// NOTE: the SQL is not always safe to execute, GORM only uses it for logs, it might cause SQL injection db.Dialector.Explain(stmt.SQL.String(), stmt.Vars...) // SELECT * FROM `users` WHERE `id` = 1
// globally mode, all DB operations will create prepared statements and cache them db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{ PrepareStmt: true, })
tx.First(&user) // SELECT * FROM users ORDER BY id LIMIT 1
tx.First(&user, "id = ?", 10) // SELECT * FROM users WHERE id = 10 ORDER BY id
// Without option `NewDB` tx2 := db.Where("name = ?", "jinzhu").Session(&gorm.Session{}) tx2.First(&user) // SELECT * FROM users WHERE name = "jinzhu" ORDER BY id
db.Session(&gorm.Session{QueryFields: true}).Find(&user) // SELECT `users`.`name`, `users`.`age`, ... FROM `users` // with this option // SELECT * FROM `users` // without this option