dongqiaozhe5070 2015-03-26 03:15
浏览 53
已采纳

如何将查询记录到数据库驱动程序?

I am trying to write a simple Database application in go which access multiple data servers, some MySQL, MSSQL and SqlLite3. I am using the "database/sql" package to access them.

db, err := sql.Open(driver, dataSourceName)
result, err := db.Exec(
    "INSERT INTO users (name, age) VALUES (?, ?)",
    "gopher",
    27,
)

I need to log the SQL queries to the individual servers for debugging and auditing. How can I achieve that?

  • 写回答

1条回答 默认 最新

  • douzuqin3467 2015-03-26 09:45
    关注

    Assuming that you don't want to use the servers logging facilities, the obvious solution would be to simply log all queries as they are made.

    db, err := sql.Open(driver, dataSourceName)
    log.Println(dataSourceName, "INSERT INTO users (name, age) VALUES (?, ?)", "gopher", 27)
    result, err := db.Exec(
        "INSERT INTO users (name, age) VALUES (?, ?)",
        "gopher",
        27,
    )
    

    This is the basic solution for your problem. You can refine it in multiple ways:

    • Create a log.Logger exclusively for your queries, so you can direct it to a particular output destination
    • Wrap the said log.Logger and the sql.DB objects in a special struct that will log queries as they are done

    Here is a rough example of the said struct:

    type DB struct {
        db *sql.DB
        dsn string
        log *log.Logger
    }
    
    func NewDB(driver, dsn string, log *log.Logger) (*DB, error) {
        db, err := sql.Open(driver, dsn)
        if err != nil {
            return nil, err
        }
    
        return &DB {
            db: db,
            dsn: dsn,
            log: log,
        }
    }
    
    func (d DB) Exec(query string, args ...interface{}) (sql.Result, err) {
        d.log.Println(dsn, query, args)
        return d.db.Exec(query, args...)
    }
    

    And how you would use it:

    l := log.New(os.Stdout, "[sql]", log.LstdFlags)
    
    db, _ := NewDB(driver, dataSourceName, l)
    result, _ := db.Exec(
        "INSERT INTO users (name, age) VALUES (?, ?)",
        "gopher",
        27,
    )
    

    Obviously, you can refined this design again, by adding error reporting, duration of the queries, etc.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊