【问题标题】:How to use for loops to do multiple SQL statements in python如何使用for循环在python中执行多个SQL语句
【发布时间】:2011-02-10 16:46:37
【问题描述】:

我有 SQl 语句列表,当运行单个语句时,它运行它给出的循环:

pyodbc.ProgrammingError: ('42000', "[42000] [MySQL][ODBC 5.1 Driver][mysqld-5.5.8]您的 SQL 语法有误;请查看与您的 MySQL 服务器版本对应的手册在第 1 行的“Sql_2”附近使用正确的语法 (1064) (SQLExecDirectW)")

SQl = """Select something"""
    SQl_2 = """Select something"""
    SQl_3 = """Select something"""


Sqls= ('Sql','Sql_2','Sql_3')

for x in Sqls:
    print x
    use = Sql_2  
    # use = x
    cxn = pyodbc.connect('DSN=MySQL;PWD=xxx') 
    csr = cxn.cursor()
    csr.execute(use)
    fetch = csr.fetchall()

【问题讨论】:

    标签: python for-loop


    【解决方案1】:

    你的元组应该是

    Sqls = (Sql,Sql_2,Sql_3)
    

    而不是

    Sqls = ('Sql','Sql_2','Sql_3')
    

    【讨论】:

    • 这可以通过在for 循环中创建元组来变得更加简单:for x in (Sql, Sql_2, Sql_3): ...
    【解决方案2】:

    您应该另外移动到数据库的连接以及在 for 循环之外创建一个游标,因为这是不必要的开销。

    SQl = """Select something"""
    SQl_2 = """Select something"""
    SQl_3 = """Select something"""
    
    Sqls = (Sql, Sql_2, Sql_3)
    cxn = pyodbc.connect('DSN=MySQL;PWD=xxx') 
    csr = cxn.cursor()
    
    for x in Sqls:
        print x
        use = Sql_2  
        # use = x    
        csr.execute(use)
        fetch = csr.fetchall()

    【讨论】:

      猜你喜欢
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 2017-05-26
      • 2016-09-02
      • 2021-12-24
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多