我想转义构成数据库查询一部分的值,但不能使用参数化查询。
Go是否具有可用来转义查询值的PHP的mysql_real_escape_string
的等效项?
最佳答案
我想出了自己的解决方案来自己创建函数。
希望对某人有用。
func MysqlRealEscapeString(value string) string {
replace := map[string]string{"\\":"\\\\", "'":`\'`, "\\0":"\\\\0", "\n":"\\n", "\r":"\\r", `"`:`\"`, "\x1a":"\\Z"}
for b, a := range replace {
value = strings.Replace(value, b, a, -1)
}
return value;
}
1.MysqlRealEscapeString不正确,如下测试用例会失败func TestEscape(t *testing.T) {
mysqlEscapeList := map[string]string{
"\\": "\\\\", "'": `\'`, "\\0": "\\\\0", "\n": "\\n", "\r": "\\r", `"`: `\"`, "\x1a": "\\Z"}
for old, want := range mysqlEscapeList {
testEscape(t, old, want)
}
testEscape(t, `<p>123</p><div><img width="1080" />`, `<p>123</p><div><img width=\"1080\" />`)
}
func testEscape(t *testing.T, origin, want string) {
escaped := MysqlRealEscapeString(origin)
assert.Equal(t, want, escaped)
}
func Escape(sql string) string {
dest := make([]byte, 0, 2*len(sql))
var escape byte
for i := 0; i < len(sql); i++ {
c := sql[i]
escape = 0
switch c {
case 0: /* Must be escaped for 'mysql' */
escape = '0'
break
case '\n': /* Must be escaped for logs */
escape = 'n'
break
case '\r':
escape = 'r'
break
case '\\':
escape = '\\'
break
case '\'':
escape = '\''
break
case '"': /* Better safe than sorry */
escape = '"'
break
case '\032': //十进制26,八进制32,十六进制1a, /* This gives problems on Win32 */
escape = 'Z'
}
if escape != 0 {
dest = append(dest, '\\', escape)
} else {
dest = append(dest, c)
}
}
return string(dest)
}
关于security - 相当于Golang的mysql_real_escape_string,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31647406/