MySQL requires tables that shadow reserved words to be back ticked. I have a table Role which is a reserved word, but I have already put my query in back ticks so I can writ
I just used a placeholder (like %s
) instead of the backticks and replaced them afterwards:
strings.ReplaceAll(`CREATE TABLE %smydatabase%s.%smytable%s (
%sid%s binary(16),
%sname%s varchar(45),
PRIMARY KEY(%sid%s)
)`, "%s", "`")
Use notepad++ on your plain text and replace (search and) replace
`
with
`+"`"+`
If your query is long, it might be worth putting in a text file and reading it in, that will keep your code more concise and organized, and also avoid the backtick quoting issue entirely.
You cannot escape backticks inside backticks, but you can do:
dbmap := db.InitDb()
var roles []entities.Role
query := `
SELECT *
FROM ` + "`Role`"
_, err := dbmap.Select(&roles, query, nil)
if err != nil {
panic(err)
}
fmt.Println(roles)
You can use .
prefix:
query := `
SELECT *
FROM .Role
`
You can try writing queries like this:
query :=fmt.Sprintf("SELECT * FROM `Role`")
You can compare the outputs:
import "fmt"
func main() {
query :=fmt.Sprintf("SELECT * FROM `Role`")
fmt.Println(query)
fmt.Println( `SELECT * FROM ` + "`Role`") }