Use sqlalchemy's text function to remove the interpretation of special characters:
Note the use of the function text("your_insert_statement") below. What it does is communicate to sqlalchemy that all of the questionmarks and percent signs in the passed in string should be considered as literals.
import sqlalchemy
from sqlalchemy import text
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import re
engine = sqlalchemy.create_engine("mysql+mysqlconnector://%s:%s@%s/%s"
% ("your_username", "your_password", "your_hostname_mysql_server:3306",
"your_database"),
pool_size=3, pool_recycle=3600)
conn = engine.connect()
myfile = open('access2.log', 'r')
lines = myfile.readlines()
penguins = []
for line in lines:
elements = re.split('\s+', line)
print "item: " + elements[0]
linedate = datetime.fromtimestamp(float(elements[0]))
mydate = linedate.strftime("%Y-%m-%d %H:%M:%S.%f")
penguins.append(text(
"insert into your_table (foobar) values('%%%????')"))
for penguin in penguins:
print penguin
conn.execute(penguin)
conn.close()
db_cur.execute('''UPDATE test_table SET field_1="%s" WHERE field_2="%s"''' % (data, condition))Note the triple single quotes and double quotes around%s- zelusp%mark in your code be a,comma, otherwise it's just the same? @zelusp - Artemis% (data, condition)is taking the variablesdataandconditionand putting it into the two%splaceholders. - zeluspconditionwere, for example," or 1 == 1 or", for example, you would have a problem.cur.executeprovides escaping by doingcur.execute('SOME COMMAND ?', [value]).?is replaced with value. - Artemis