使用 MySQLdb 执行多个 SQL 查询

发布于 2024-10-10 19:31:23 字数 2606 浏览 3 评论 0 原文

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

Don'不知道这是否是最好的解决方案,但似乎解析 SQL 语句不太复杂,

现在的问题是如何运行此代码,我可以执行类似 这家伙但这看起来很难看,我不是Python专家(我们一直在做python 刚刚过去两周),但似乎以这种方式滥用光标是黑客行为,而不是一个好的做法,

谢谢你,
格言。

How would you go about executing several SQL statements (script mode) with 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)

Fails with:

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

I'm writing an deployment engine that would accept SQL delta changes from several people and apply them to the DB on version deployment.

I've looked into this code http://sujitpal.blogspot.com/2009/02/python-sql-runner.html and implemented __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)

Don't know if it's the best solution but seems to work for not too complex to parse SQL statements.

The question now how to run this code, I can do something like this dude but it seems ugly, I'm not a python expert (we've been doing python here for just the past 2 weeks) but it seems that abusing cursor this way is hackish and not a good practice.

Ideas / blog posts would be helpful.

Thanks you,
Maxim.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒绊 2024-10-17 19:31:23

以下是如何使用 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()

Here is how you could use 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()
稍尽春風 2024-10-17 19:31:23

对游标对象调用executemany 方法。更多信息请点击这里:
http://mysql-python.sourceforge.net/MySQLdb.html

Call the executemany method on the cursor object. More info here:
http://mysql-python.sourceforge.net/MySQLdb.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文