3 回答
TA贡献1836条经验 获得超3个赞
我想出了自己的解决方案来自己创建函数。
希望它对某人有用。
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)
}
TA贡献1860条经验 获得超8个赞
改进的答案:
func MysqlRealEscapeString(value string) string {
var sb strings.Builder
for i := 0; i < len(value); i++ {
c := value[i]
switch c {
case '\\', 0, '\n', '\r', '\'', '"':
sb.WriteByte('\\')
sb.WriteByte(c)
case '\032':
sb.WriteByte('\\')
sb.WriteByte('Z')
default:
sb.WriteByte(c)
}
}
return sb.String()
}
- 3 回答
- 0 关注
- 180 浏览
添加回答
举报