使用MySQLdb执行多个SQL查询

3 投票
2 回答
6814 浏览
提问于 2025-04-16 09:30

你怎么用Python执行多个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)

但是出现了这个错误:

编程错误: (2014, "命令不同步;你现在不能运行这个命令")

我正在写一个部署引擎,它可以接受来自不同人的SQL增量变更,并在版本部署时应用到数据库中。

我查看了这段代码 http://sujitpal.blogspot.com/2009/02/python-sql-runner.html,并实现了 __sanitize_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语句解析是有效的。

现在的问题是怎么运行这段代码,我可以像这个人那样做,但看起来不太好,我并不是Python专家(我们在这里才学了两周的Python),但感觉这样使用游标有点像是变通,不是个好习惯。

如果有想法或博客文章分享就太好了。

谢谢你,
Maxim。

2 个回答

0

在光标对象上调用 executemany 方法。想了解更多信息,可以查看这里: http://mysql-python.sourceforge.net/MySQLdb.html

1

下面是你可以使用 executemany() 的方法:

import MySQLdb
connection = MySQLdb.connect(host='host...rds.amazonaws.com', db='dbName', user='userName', passwd='password')
cursor = connection.cursor()

my_data_to_insert = [['maxim0', 'was here0'], ['maxim1', 'was here1'], ['maxim2', 'was here1']]
sql = "insert into rollout.version (`key`, `value`) VALUES (%s, %s);"

cursor.executemany(sql, my_data_to_insert)

connection.commit()
connection.close()

撰写回答