golang mysql exec占位符“?"没有扩展 [英] golang mysql exec placeholder "?" not expanded

查看:79
本文介绍了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)

还有,谁在关注它的扩展?它显示在 database/sql doc 中,但其他对话暗示这可能是驾驶员担心的问题.

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.

推荐答案

(可能)您没有告诉它使用mysql驱动程序;

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

我用以下方法创建MySQL池(是的,它是一个没有连接的池):

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.

这篇关于golang mysql exec占位符“?"没有扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆