简体   繁体   中英

How to insert user input to Postgres Db with Go

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.

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. ie:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM