1

尝试^使用 python 2.4.3 将分隔文件导入 DB2 数据库时出现以下错误。

错误:

Traceback (most recent call last):
  File "C:\Python25\Usefulscripts\order.py", line 89, in <module>
    load_order_stack() 
  File "C:\Python25\Usefulscripts\order.py", line 75, in load_order_stack
    conn2.execute(importTmp)
ProgrammingError: ('42601', '[42601] [IBM][CLI Driver][DB2/LINUXX8664] SQL0104N  An unexpected token "orders_extract"

在“import from”之后发现。

代码:

import pyodbc

def load_order_stack():
    try:
        conn2 = pyodbc.connect('DSN=db2Database;UID=ueserid;PWD=password')
        importTmp = ("import from orders_extract of del modified by coldel0x5E"
                     "insert_update into test.ORDERS_Table (ORDER_ID,item,price);")
        conn2.execute(importTmp)
        conn2.commit()
4

2 回答 2

2

IMPORT 不是 SQL 语句。它是一个 DB2 命令行处理器 (CLP) 命令,因此只能由所述 CLP 运行。

通过调用 ADMIN_CMD() 存储过程,一些 CLP 命令有一个 SQL 接口,请查看手册:IMPORT using ADMIN_CMD

于 2013-05-15T11:43:24.387 回答
1

您还可以选择逐行读取文件并插入到数据库中。这肯定会比任何本机导入操作都慢。假设您的分隔文件结构是,并且文件名为input.txt

ORDER_ID^item^price
1^'bat'^50.00
2^'ball'^25.00

代码:

import csv
import pyodbc

connection = pyodbc.connect('DSN=db2Database;UID=ueserid;PWD=password')
cursor = connection.cursor()

with open('input.txt', 'rb') as f:
    rows = csv.reader(f, delimiter='^')
    # get column names from header in first line
    columns = ','.join(next(rows))
    for row in rows:
        # build sql with placeholders for insert
        placeholders = ','.join('?' * len(row))
        sql = 'insert into ({}) values ({});'.format(columns, placeholders)

        # execute parameterized database insert
        cursor.execute(sql, row)
        cursor.commit()

玩转commit()放置,您可能希望分批提交以提高性能。

于 2013-05-15T13:34:43.547 回答