Home > Blockchain >  Dynamic SQL Set Golang
Dynamic SQL Set Golang

Time:01-27

I have a doubt about the structure of a SQLite query. I'm trying to update a user-selected value in the table referencing the row by the username. The table is called Data and has these columns: USERNAME,PASSWORD,ADDRESS,NOTES.

I'm using SQL drivers for GO (_ "github.com/mattn/go-sqlite3"), here's my query:

...
stmt, err := db.Prepare("UPDATE Data SET ?=? WHERE USERNAME=?")
check(err)
res, err := stmt.Exec(splittedQuery[0], splittedQuery[1],splittedQuery[2])
...

From this sequence I can only get a syntax error: near "?": syntax error. How should I manage this? If it's a trivial question I'm sorry, I'm just new to GO and trying to learn something out of it.

Thanks

CodePudding user response:

You cannot do that in SQL. It's not specific to sqlite either. Parameterized placeholder are only for value, you cannot change the structure of the query with that. Here are some documentation links for your reference:

What you are trying to do is building a dynamic query. You can do that by building your query string yourself:

query := "UPDATE Data SET "   col_name   "=? WHERE USERNAME=?"

But depending from the source of your data for the column_name you need to be cautious of sql injection (this is a whole other topic, for fun you can look at that https://imgs.xkcd.com/comics/exploits_of_a_mom.png).

There are also a few library available to help you with that. For example to name one, you can check this one https://github.com/Masterminds/squirrel

  • Related