title: How can I escape the input to a MySQL db in Python3?
body: <p>How can I escape the input to a MySQL db in Python3?
  I'm using PyMySQL and works fine, but when I try to do something like:</p>
  
  <pre><code>cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` =  '{}'".format(request[1]))
  </code></pre>
  
  <p>it won't work if the string has <code>'</code> or <code>"</code>. I also tried:</p>
  
  <pre><code>cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` =  %s",request[1])
  </code></pre>
  
  <p>The problem with this is that the library (PyMySQL) uses the formatting syntax for Python2.x, <code>%</code>, that doesn't work anymore.
  I also found this possible solution</p>
  
  <pre><code>conn.escape_string()
  </code></pre>
  
  <p>in <a href="https://stackoverflow.com/a/3617097/1460016">here</a>, but I don't know where to add this code.
  This is all I got:</p>
  
  <pre><code>import pymysql
  import sys
  conn = pymysql.connect( host   = "localhost",
              user   = "test",
              passwd = "",
              db     = "test")
  cursor = conn.cursor()
  cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` =  {}".format(request[1]))
  
  result = cursor.fetchall()
  
  cursor.close()
  conn.close()
  </code></pre>
  
  <p>Edit: I solved it! In PyMySQL the right way is like this:</p>
  
  <pre><code>import pymysql
  import sys
  conn = pymysql.connect(host="localhost",
              user="test",
              passwd="",
              db="test")
  cursor = conn.cursor()
  text = conn.escape(request[1])
  cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` =  {}".format(text))
  
  cursor.close()
  conn.close()
  </code></pre>
  
  <p>Where the <code>text = conn.escape(request[1])</code> line is what escapes the code. Found it inside PyMySQL code. There, <code>request[1]</code> is the input.</p>