Skip to content

Instantly share code, notes, and snippets.

@CTimmerman
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CTimmerman/9bcf0f9de27456f6859e to your computer and use it in GitHub Desktop.
Save CTimmerman/9bcf0f9de27456f6859e to your computer and use it in GitHub Desktop.
batch replace / escape SQL previewer
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
@CTimmerman
Copy link
Author

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')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment