title: How to insert strings with quotes and newlines into sqlite db with Python?
body: <p>I'm trying to insert strings read from a file into an <code>sqlite</code> database in Python. The strings have whitespace (newline, tab characters, and spaces) and also have appearances of single or double quotes.  Here's how I try to do it:</p>
  
  <pre><code>import sqlite3
  conn = sqlite3.connect('example.db')
  c = conn.cursor()
  
  # Create table
  c.execute('''CREATE TABLE test
               (a text, b text)''')
  
  f = open("foo", "w")
  f.write("hello\n\'world\'\n")
  f.close()
  
  testfield = open("foo").read()
  
  # Insert a row of data
  c.execute("INSERT INTO test VALUES ('%s', 'bar')" %(testfield))
  
  # Save (commit) the changes
  conn.commit()
  </code></pre>
  
  <p>I find that this fails with the error: </p>
  
  <pre><code>    c.execute("INSERT INTO test VALUES ('%s', 'bar')" %(testfield))
  sqlite3.OperationalError: near "world": syntax error
  </code></pre>
  
  <p>How can I achieve this? Do the strings need to be escaped before insertion in the db, and if so how? thanks.</p>