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.

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

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题