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 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)
  • ¥20 web页面如何打开Outlook 365的全球离线通讯簿功能
  • ¥15 io.jsonwebtoken.security.Keys
  • ¥15 急,ubuntu安装后no caching mode page found等
  • ¥15 联想交换机NE2580O/NE1064TO安装SONIC