douruanfan3030 2016-03-03 19:43
浏览 411
已采纳

golang mysql exec占位符“?”未扩展

I feel like I must be totally missing the point. I try to run something along the lines of the example below, but the ? is not expanded into the argument passed in.

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

db, err := sql.Open(...)
if err != nil { ... }
_, err = db.Query("SELECT * FROM foo WHERE bar=?", bar)

Also, who's concern is expanding it? it show's up in the doc of database/sql but other conversations hinted it may be the concern of the driver.

What am I missing? Any pointer in the right direction is greatly appreciated.

  • 写回答

1条回答 默认 最新

  • dt3358 2016-03-03 19:55
    关注

    You're (probably) not telling it to use the mysql driver;

    db, err := sql.Open("mysql", connString)
    

    Here is some of my sample code:

    var query = "INSERT IGNORE INTO blah (`col1`, `col2`, `col3`) VALUES (?, ?, ?)"
    
    r, err := db.Query(query, some_data_1, some_data_2, some_data_3)
    
    // Failure when trying to store data
    if err != nil {
        msg := fmt.Sprintf("fail : %s", err.Error())
        fmt.Println(msg)
    
        return err
    }
    
    r.Close() // Always do this or you will leak connections
    

    I create the MySQL pool (yes, it's a pool NOT a connection) with:

    import (
        // mysql driver
        _ "github.com/go-sql-driver/mysql"
    
        "database/sql"
        "fmt"
    )
    
    connString := fmt.Sprintf("%s:%s@(%s:%d)/%s?timeout=30s",
        user,
        password,
        host,
        port,
        database,
    )
    
    db, err := sql.Open("mysql", connString)
    
    if err != nil {
        return nil, err
    }
    
    err = db.Ping() // test the pool connection(s)
    
    if err != nil {
        return nil, err
    }
    
    return db, nil // No error, return the pool connections
    

    I also highly suggest you print out any errors in the database connection process and query process. It could be that you are using the driver, but you lack permissions, the database is down, etc.

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

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装