2011-01-06 5 views
3

PythonでいくつかのSQL文(スクリプトモード)を実行するにはどうしますか?私はいくつかの人々からSQLデルタ変更を承認し、DBにそれらを適用する展開エンジンを書いてMySQLdbで複数のSQLクエリを実行する

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

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を実装しました:それは最善の解決策だが、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) 

は知ってはいけません。

このコードを実行する方法は、this dudeのようにすることができますが、私はPythonのエキスパートではありません(過去2週間はここでPythonをやっています)。この方法でカーソルを乱用すると、ハックされ、良い習慣ではありません。

アイデアやブログ記事が参考になります。

ありがとう、
マキシム。

答えて

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() 
関連する問題