添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
没读研的米饭  ·  scipy.io.wavfile.read, ...·  2 年前    · 
讲道义的手链  ·  ConstraintLayout ...·  2 年前    · 

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Are only certain statements prepared? I'm going a bit crazy wondering why DB.Exec (and DB.Query) aren't preparing the following statement as I'd expect.

From go's stdlib it looks like DB.Exec can take placeholders: https://golang.org/pkg/database/sql/#DB.Exec

I'm running postgres in a docker image:

docker run -p 5432:5432 -it postgres
package main
import (
	"fmt"
	"database/sql"
	_ "github.com/lib/pq"
func main() {
	conninfo := "user=postgres host=127.0.0.1 sslmode=disable"
	db, _ := sql.Open("postgres", conninfo)
	_, err := db.Exec(`create database $1`, "foo")
	// _, err := db.Exec(`create database ?`, "foo") // doesn't work
	// _, err := db.Exec(fmt.Sprintf(`create database %s`, "foo")) // works 
	fmt.Println(err)

Output:

$ go run /tmp/db.go 
pq: syntax error at or near "$1"
          

Looking through a bunch of code on github this seems to be a common problem that people just fmt.Sprintf their way around. (At the cost of sql injection.)

Example: https://github.com/dsblox/pim/blob/e27dc2aaa4f1f322c109f54bdeecdd61fdfbc6ad/taskmapperpg.go#L105

Search: https://github.com/search?p=1&q=language%3Ago+%22db.Exec%22+%22create+database%22&type=Code&utf8=%E2%9C%93