How are you going to execute multiple SQL statements (script mode) using python?
Trying to do something like this:
import MySQLdb
mysql = MySQLdb.connect(host='host...rds.amazonaws.com', db='dbName', user='userName', passwd='password')
sql = """
insert into rollout.version (`key`, `value`) VALUES ('maxim0', 'was here0');
insert into rollout.version (`key`, `value`) VALUES ('maxim1', 'was here1');
insert into rollout.version (`key`, `value`) VALUES ('maxim2', 'was here1');
"""
mysql.query(sql)
Failure:
ProgrammingError: (2014, "Commands out of sync; you cannot run this command now")
I am writing a deployment mechanism that will accept SQL delta changes from multiple users and apply them to the database when deploying the version.
I looked at this code http://sujitpal.blogspot.com/2009/02/python-sql-runner.html and implemented __sanitize_sql:
def __sanitize_sql(sql):
sql_statements = []
incomment = False
in_sqlcollect = False
sql_statement = None
for sline in sql.splitlines():
sline = sline.strip()
if sline.startswith("--") or len(sline) == 0:
continue
if sline.startswith("/*"):
incomment = True
if incomment and sline.endswith("*/"):
incomment = False
continue
if not incomment:
if sql_statement is None:
sql_statement = sline
else:
sql_statement += sline
if not sline.endswith(";"):
in_sqlcollect = True
if not in_sqlcollect:
sql_statements.append(sql_statement)
sql_statement = None
in_sqlcollect = False
if not incomment and not sql_statement is None and len(sql_statement) != 0:
sql_statements.append(sql_statement)
return sql_statements
if __name__ == "__main__":
sql = sql = """update tbl1;
/* This
is my
beautiful
comment*/
/*this is comment #2*/
some code...;
-- comment
sql code
"""
print __sanitize_sql(sql)
I don't know if this is the best solution, but it doesn't seem to work too hard for parsing SQL statements.
, , - , , python ( python 2 ), , .
/ .
,
.