英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论