在Go中编写文本SQL查询的正确方法 [英] Correct way to write a text SQL query in Go
问题描述
我找不到正确的方法来用值连接文本查询的字符串部分的好例子.例如:
I can't find a good example of the right way to concat the string portion of a text query with the values. For example:
query := `SELECT column_name FROM table_name
WHERE column1_name = %d AND column2_name = %d` % (val1, val2)
rows, res, err := db.Query(query)
这不起作用.编译器返回语法错误:意外的逗号,期望)
可能是因为我正在尝试使用python样式元组.
This doesn't work. The compiler returns syntax error: unexpected comma, expecting )
Likely because I'm trying to use a python style tuple.
如果我将其重写为
query := `SELECT column_name FROM table_name
WHERE column1_name = %d AND column2_name = %d` % val1
我得到(字符串和整数类型不匹配)
,告诉我该元组是问题之一.
I get (mismatched types string and int)
which tells me that the tuple was ONE OF the problems.
如果我首先将参数转换为字符串,则会得到(未在字符串上定义运算符%)
If I cast my parameters as strings first, I get (operator % not defined on string)
在python中,您会做类似的事情
In python, you'd do something like
query = """SELECT column_name FROM table_name
WHERE column1_name = %d
AND column2_name = %d""" % (val1, val2)
OR
query = """SELECT column_name FROM table_name
WHERE column1_name = %s
AND column2_name = %s""" % (val1_string, val2_string)
我知道我可以使用"STRING" + var +"STRING"
将值转换为字符串和concat,但是与python版本相比,这看起来确实很混乱.Go中的python代码相当于什么?具体包括元组部分,并连接字符串和整数.
I know I could just cast the values as strings and concat with "STRING" + var + "STRING"
, but that seems really messy compared to the python version. What's the equivalent of that python code in Go? Specifically including the tuple portion, and concatenating a string and an integer.
推荐答案
<关于由于注入漏洞而在SQL语句中使用字符串插值的标准建议>
< standard admonishment about using string interpolation with SQL statements because of injection vulnerabilities >
您可以使用 fmt.Sprintf
进行处理.
You can use fmt.Sprintf
to handle this.
query := fmt.Sprintf(`SELECT columnA FROM tableA WHERE columnB = %d AND columnB = %s`,
someNumber, someString)
为避免注入问题,将您的第一个代码编写为:
To avoid injection issues, write your first code as:
query := `SELECT column_name FROM table_name
WHERE column1_name = %d AND column2_name = %d`
rows, err := db.Query(query, val1, val2)
这篇关于在Go中编写文本SQL查询的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!