Home > Backend Development > Golang > How to View Underlying MySQL Queries Generated by GORM in Go?

How to View Underlying MySQL Queries Generated by GORM in Go?

Mary-Kate Olsen
Release: 2024-12-22 17:50:11
Original
577 people have browsed it

How to View Underlying MySQL Queries Generated by GORM in Go?

How to Access the Underlying MySQL Query in Go with GORM

GORM is a powerful ORM (Object-Relational Mapping) library for Go. It simplifies database interactions by providing a clean and intuitive API. However, sometimes it's useful to access the raw SQL queries that are being executed underneath. This can be especially helpful for debugging or optimizing your database interactions.

Retrieving the SQL Query Log

To get the SQL query log from GORM, you can use the LogMode method. This method takes a boolean value as an argument. If true, GORM will log the SQL queries to the console. Here's how you would use it:

package main

import (
    "gorm.io/gorm"
    "log"
)

func main() {
    db, err := gorm.Open("mysql", "user:password@tcp(localhost:3306)/database_name")
    if err != nil {
        log.Fatal(err)
    }

    // Enable log mode
    db.LogMode(true)

    var todos []Todo
    db.Find(&todos)
    db.Preload("User").Find(&todos)
}
Copy after login

By default, LogMode logs all SQL queries to the console. If you only want to log queries in certain environments, such as development, you can use the To method to specify the destination:

import (
    "fmt"
    "gorm.io/gorm/logger"
    "log"
    "os"
)

type DevLogger struct {
    logger.Interface
}

func (l *DevLogger) Printf(level logger.Level, format string, v ...interface{}) {
    if level == logger.Info || os.Getenv("ENV") == "development" {
        fmt.Println("QUERY: ", fmt.Sprintf(format, v...))
    }
}

func main() {
    db, err := gorm.Open("mysql", "user:password@tcp(localhost:3306)/database_name?parseTime=true")
    if err != nil {
        log.Fatal(err)
    }

    db.Logger = &DevLogger{Interface: logger.Discard}

    var todos []Todo
    db.Find(&todos)
    db.Preload("User").Find(&todos)
}
Copy after login

The above code uses a custom logger to only log queries in development environments (when ENV=development).

Note that in GORM v2, the DB type has been replaced with *gorm.DB. The methods and syntax for *gorm.DB are similar to those of DB, but the * indicates that it's a pointer receiver.

The above is the detailed content of How to View Underlying MySQL Queries Generated by GORM in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template