相当于Golang的mysql_real_escape_string

I would like to escape a value that makes up part of a database query, but I can't use parameterized queries.

Does Go have an equivalent of PHP's mysql_real_escape_string I can use to escape the query value?

If the entire query - or any part of the query that goes beyond a single value - is passed from the command line, there is nothing for you to escape.

mysql_real_escape_string and its cousins are for sanitizing single values, to prevent anyone with access to the value before it is inserted into the query from "breaking out" and fiddling with the query itself.

Given that you are giving access to the entire query to an outside, there is nothing an escape function could do to improve safety.

Your only shot at security here is

  • executing the query in a user context that can't do any damage (e.g. you can restrict commands on a per-user basis in mySQL)
  • making sure that query errors are properly caught and dealt with
  • as Not_a_Golfer suggests in the comments above, parsing the query for anything malicious

I came up with my own solution to create the function myself.
Hope it would be useful to someone.

func MysqlRealEscapeString(value string) string {
    replace := map[string]string{"\\":"\\\\", "'":`\'`, "\\0":"\\\\0", "
":"\
", "":"\", `"`:`\"`, "\x1a":"\\Z"}

    for b, a := range replace {
        value = strings.Replace(value, b, a, -1)
    }

    return value
}