How to insert user input to Postgres Db with Go

huangapple go评论71阅读模式
英文:

How to insert user input to Postgres Db with Go

问题

我正在尝试将一个字符串插入到Postgres数据库中,但是我找不到正确的语法。以下是代码:

func insertdb() {
    fmt.Println("Write your text")
    var input string
    fmt.Scanln(&input)
    insertstmt := `insert into "todos"("do_info") values($1)`
    _, e := DB.Exec(insertstmt, input)
    checkError(e)
}

我想将变量input插入到我的Postgresql数据库中。在SQL查询的values后面应该如何编写?

values($1)

错误提示需要一个参数。

英文:

I am trying to insert a string to a Postgres database. And I couldn't find the correct syntax. Here is the code:

func insertdb() {
	fmt.Println("Write your text")
	var input string
	fmt.Scanln(&input)
	insertstmt := `insert into "todos"("do_info") values(**I need this**)`
	_, e := DB.Exec(insertstmt)
	checkError(e)
}

I want to insert the input variable to my Postgresql database. How should I write it after values in sql query?

values($1)

Error says need a parameter.

答案1

得分: 3

你的代码报错是因为查询中有一个占位符$1,但在Exec函数中没有传递相应的参数。

你需要将输入传递给Exec函数,以便它可以替换占位符。例如:

    fmt.Println("写入你的文本")
    var input string
    fmt.Scanln(&input)
    insertstmt := `insert into todos (do_info) values($1)`
    _, err = DB.Exec(insertstmt, input)
英文:

Your code complains beacause the query has a placeholder $1 and it does not have a matching argument passed to the Exec function.

You have to pass the input to the Exec function so that it can replace the placeholder. i.e:

    fmt.Println("Write your text")
    var input string
    fmt.Scanln(&input)
    insertstmt := `insert into todos (do_info) values($1)`
    _, err = DB.Exec(insertstmt, input)

huangapple
  • 本文由 发表于 2022年12月16日 20:07:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/74824250.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定