Node MySQL escape LIKE statement

后端 未结 4 1714
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 04:33

How do escape a MySQL LIKE statement in node-mysql?

Something along the lines of

\"SELECT * FROM card WHERE name LIKE \'%\" + connection.escape(req.b         


        
相关标签:
4条回答
  • 2020-12-15 04:35

    Not sure why it's escaping the % in your last example, because that works fine for me:

    // lifted from my code:
    var value = 'ee20e966289cd7';
    connection.query('SELECT * from django_session where session_key like ?', '%' + value + '%', ...)
    
    // Result:
    [ { session_key: '713ee20e966289cd71b936084a1e613e', ... } ]
    

    When I turn on debugging in the driver (pass debug:true as argument to mysql.createConnection), it doesn't escape the percent sign:

    { command: 3,
      sql: 'SELECT * from django_session where session_key like \'%ee20e966289cd7%\'' }
    

    (it does escape the single quote, but that's for display purposes only)

    (using mysql@2.0.0-alpha8)

    0 讨论(0)
  • 2020-12-15 04:36

    i've had success with something like

    "SELECT * FROM card WHERE name LIKE " + connection.escape('%'+req.body.search+'%')
    
    0 讨论(0)
  • 2020-12-15 04:46

    How about

    mysql.format("SELECT * FROM card WHERE name LIKE CONCAT('%', ?,  '%')", req.body.search)
    

    ?

    0 讨论(0)
  • 2020-12-15 05:00

    you can always do

    variable = '%${variable}%'
    "SELECT * FROM 'table' WHERE ('foo' LIKE ?);", 
    [variable], callback =>
    
    0 讨论(0)
提交回复
热议问题