2011-01-06 208 views
3

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

與失敗在版本部署上。

我看着這個代碼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),但似乎以這種方式濫用光標是不好的做法。

想法/博客文章會有幫助。

謝謝你,
Maxim。

回答

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()