python - 使用 MySQLdb 执行多个 SQL 查询

标签 python sql batch-processing sql-scripts

您将如何使用 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)

失败:

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

我正在编写一个部署引擎,它可以接受来自多个人的 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 语句解析。

现在的问题是如何运行这段代码,我可以做类似 this dude 的事情但这看起来很丑陋,我不是 Python 专家(过去 2 周我们一直在这里使用 Python),但似乎以这种方式滥用游标是骇人听闻的,不是一个好的做法。

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

谢谢你,
格言。

最佳答案

这里是你如何使用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()

关于python - 使用 MySQLdb 执行多个 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4615271/

相关文章:

sql - 在重复的列上分组

java - Spring Batch 在运行步骤之前解析步骤的资源

python - Theano 的 Scan 函数复制 non_sequences 共享变量

python - 对 4D numpy 数组进行排序,但保持一个轴连接在一起

python - Django 休息框架 : Filter/Validate Related Fields

SQL - 如何只获取小数点后的数字?

python - 以表格格式写入 csv 文件

sql - 格式pandas.Timestamp用于SQLite查询

python - 批处理 : GNU-make, Snakemake 还是什么?

apache-spark - Spark 流 : long queued/active batches