Last active
August 29, 2015 14:18
-
-
Save CTimmerman/9bcf0f9de27456f6859e to your computer and use it in GitHub Desktop.
batch replace / escape SQL previewer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sql_escape(v): | |
return "'"+str(v).replace("'", "''")+"'" | |
def fill_sql(sql, values): | |
"Hacking around hard-to-reproduce pypyodbc bug. Also using tinyint for bools for easy counting." | |
unique = "%PARAMETER%" | |
sql = sql.replace("?", unique) | |
for v in values: sql = sql.replace(unique, "null" if repr(v)=="None" else str(int(v)) if type(v) == bool else repr(v) if type(v) in (int, float) else sql_escape(v), 1) | |
return sql | |
sql = "update table set bla=?, bla2=?, bla3=? where id=?" | |
vals = ["Bob", "Joe?", "It's hard", 5] | |
print(fill_sql(sql, vals)) # update table set bla='Bob', bla2='Joe?', bla3='It''s hard' where id=5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The bug i could not repro in a smaller program:
id = vals[0]
sql_preview = fill_sql(combined_sql, [id] + vals[1:]+[id] + vals)
return cur.execute(sql_preview).rowcount # works fine.
return cur.execute(combined_sql, [id] + vals[1:]+[id] + vals).rowcount # pypyodbc.DataError: ('22018', '[22018] [Microsoft][ODBC SQL Server Driver][SQL Server]Operand type clash: int is incompatible with datetimeoffset')