python3 mysqldb查询_使用MySQLdb执行多个SQL查询

如何使用python执行几个SQL语句(脚本模式)?使用MySQLdb执行多个SQL查询

试图做这样的事情:

ProgrammingError: (2014, "Commands out of sync; you can't run this command now")

我正在写将接受从几个人的SQL增量更改,并将它们应用到数据库的部署引擎:

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)

与失败在版本部署上。

def __sanitize_sql(sql):

# Initial implementation from http://sujitpal.blogspot.com/2009/02/python-sql-runner.html

sql_statements = []

incomment = False

in_sqlcollect = False

sql_statement = None

for sline in sql.splitlines():

# Remove white space from both sides.

sline = sline.strip()

if sline.startswith("--") or len(sline) == 0:

# SQL Comment line, skip

continue

if sline.startswith("/*"):

# start of SQL comment block

incomment = True

if incomment and sline.endswith("*/"):

# end of SQL comment block

incomment = False

continue

# Collect line which is part of

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)

不知道这是最好的解决方案,但似乎对于不太复杂解析SQL语句的工作。

现在的问题是如何运行这段代码,我可以做一些类似于this dude的东西,但它看起来很丑,我不是一个Python专家(我们在这里只是在过去的2周里一直在做python),但似乎以这种方式滥用光标是不好的做法。

想法/博客文章会有帮助。

谢谢你,

Maxim。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值