dongzhi6463
2019-04-20 00:27
浏览 87

golang mysql驱动程序无法替换参数

OS Mojave, MySQL v8.0.15, go 1.12.3 darwin/amd64

import (
    "database/sql"

    // import mysql driver anonymously (just run the init)
    _ "github.com/go-sql-driver/mysql"
)

...

_, err = db.db.Exec("USE ?", "test")
if err != nil {
    return errors.Wrapf(err, "error selecting database %s", opt.Database)
}

_, err = db.db.Prepare("SELECT value FROM ? WHERE key = ?")
if err != nil {
    return errors.Wrap(err, "error generating SELECT statement")
}

The error I get is error selecting database test: Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1

I get the same error (about syntax around '?') for any parameter replacement I attempt to do. I've checked the manual as well as tutorials and examples I've found online and can't quite tell what I'm doing wrong.

If I replace the '?'s with values (strings) then everything works fine.

图片转代码服务由CSDN问答提供 功能建议

OS Mojave, MySQL v8.0.15, go 1.12.3 darwin / amd64 \ n

  import(
“ database / sql” 
 
 //匿名导入mysql驱动程序(只需运行init)
 _“ github.com/go-sql-driver/mysql"
  )
 
 ... 
 
_,err = db.db.Exec(“ USE?”,“ test”)
if err!= nil {
返回错误。Wrapf(err,“错误选择数据库 %s“,opt.Database)
} 
 
_,err = db.db.Prepare(” SELECT value FROM?WHERE key =?“)
if err!= nil {
返回错误。Wrap(err  ,“生成SELECT语句时出错”)
} 
   
 
 

我得到的错误是选择数据库测试时出错:错误1064:您的错误 SQL语法; 检查与您的MySQL服务器版本相对应的手册,以在'?'附近使用正确的语法。 在第1行

,我尝试执行的任何参数替换操作都遇到相同的错误(关于'?'周围的语法)。 我已经检查了手册以及在线上找到的教程和示例,但无法完全判断自己在做什么。

如果我将“?”替换为值(字符串),则一切正常。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douwaif22244 2019-04-20 11:59
    已采纳

    Question marks ? in prepared statements are for values, not table, database or column names.

    Use fmt.Sprintf to fill in the database structure related values.

    Example:

    _, err := db.db.Prepare(fmt.Sprintf("SELECT value FROM %s WHERE key = ?", table))
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题