Home  >  Article  >  Backend Development  >  Dynamic SQL Set Golang

Dynamic SQL Set Golang

WBOY
WBOYforward
2024-02-11 09:24:19999browse

动态 SQL 集 Golang

#php editor Xinyi today introduces you to a powerful development tool - dynamic SQL set Golang. Golang is a modern programming language that is easy to learn, efficient and fast. Dynamic SQL Set Golang combines the advantages of the Golang language and the flexibility of dynamic SQL to provide developers with a simple and powerful way to handle SQL queries and operate databases. By using the dynamic SQL set Golang, developers can more easily build dynamic SQL queries and be able to dynamically generate SQL statements to adapt to different query needs. Whether developing small projects or large applications, the dynamic SQL set Golang can help developers handle database operations more efficiently and improve development efficiency.

Question content

I have a question about the structure of sqlite query. I'm trying to update a user-selected value in a table that references a row by username. The table is named data and has the following columns: username, password, address, notes.

I'm using go's sql driver (_ "github.com/mattn/go-sqlite3") and this is my query:

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

I can only get one syntax error from this sequence: near "?": syntax error . How should I handle this problem? I'm sorry if this is a trivial question, I'm just new to go and trying to learn something from it.

Thank you

Workaround

You cannot do this in sql. It's not sqlite specific either. Parameterized placeholders are used only for values, you cannot use them to change the structure of the query. Here are some documentation links for your reference:

What you want to do is build a dynamic query. You can do this by building the query string yourself:

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

But depending on the data source of column_name, you need to be wary of sql injection (this is a completely different topic, for fun you can take a look https://imgs.xkcd.com/comics/exploits_of_a_mom.png).

There are also libraries that can help you achieve this. For example, to give an example, you can check this https://www.php.cn/link/2d16ad1968844a4300e9a490588ff9f8

The above is the detailed content of Dynamic SQL Set Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete