How to escape back ticks

前端 未结 6 501
感动是毒
感动是毒 2020-11-28 12:00

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

相关标签:
6条回答
  • 2020-11-28 12:05

    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", "`")
    
    0 讨论(0)
  • 2020-11-28 12:07

    Use notepad++ on your plain text and replace (search and) replace

    `
    

    with

    `+"`"+`
    
    0 讨论(0)
  • 2020-11-28 12:19

    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.

    0 讨论(0)
  • 2020-11-28 12:21

    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)
    
    0 讨论(0)
  • 2020-11-28 12:24

    You can use . prefix:

    query := `
    SELECT *
    FROM .Role
    `
    
    0 讨论(0)
  • 2020-11-28 12:29

    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`") }
    
    0 讨论(0)
提交回复
热议问题