1

大量のSQLクエリ(挿入)を含むテキストファイルをロードし、Python(PYODBC)を使用して実行したい

私の現在のコードは次のようになります。

cursor = cnxn.cursor()
with open('C:\Python_Script_Test\INSERTS.txt','r') as file:
    var1 = file.read().replace("\r\n","")
var2 = var1

cursor.execute(var2)
file.close()

そのファイルには 5000 行以上あり、そこからの INSERT の例は次のようになります。

Insert into x (q, w, e, r, t, y, u, i, o, p, a, s, d, f, g, h, j)
  VALUES (582, 'GA26', 'TMO ', 'xxx', 'xxx@example.com', '', 'NULL', 'NULL', 
  '', '', '', '', '', '', '', '', NULL);

エラー:

pyodbc.ProgrammingError: ('42000', 
  "[42000] [MySQL][ODBC 3.51 Driver][mysqld-5.6.13]
  You have an error in your SQL syntax; check the manual that corresponds to 
  your MySQL server version for the right syntax to use near 
  'insert into x
   (z, b, c, d, e' at line 3 (1064) (SQLExecDirectW)")

編集:

別のアイデア:

OK、今のところエラーはありません。現在のコードは次のようになります。 )
if y.startswith('insert'):
前を印刷 if previous.endswith(';'): print 'test\r\n' cursor.execute(previous)
previous = y
else: previous += y

しかし、データベースのテーブルに変更はありません...

4

2 に答える 2

2

Python を使用する必要があることは理解していますが、ファイル全体を一度に実行する必要があるかどうかは明確ではありません。入力ファイルはすでに行に分割されているため、次のようになります。

cursor = cnxn.cursor()
with open('C:\Python_Script_Test\INSERTS.txt','r') as inserts:
    for statement in inserts:
        cursor.execute(statement)

また、Python で変数名として使用することは、組み込みをfile上書きするため、悪い考えです。file()

于 2013-09-10T12:32:20.100 に答える