[英]Error while importing file into DB2 from python script
Getting the below error while trying to import a ^
delimited file into a DB2 database using python 2.4.3. 尝试使用python 2.4.3将
^
分隔的文件导入DB2数据库时出现以下错误。
Error: 错误:
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"
was found following "import from ".
在“从...导入”之后被发现。
Code: 码:
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()
IMPORT is not an SQL statement. IMPORT不是SQL语句。 It is a DB2 Command Line Processor (CLP) command and as such can only be run by the said CLP.
这是一个DB2命令行处理器(CLP)命令,因此只能由该CLP运行。
There is an SQL interface to some CLP commands via calls to the ADMIN_CMD() stored procedure, please check the manual: IMPORT using ADMIN_CMD 通过调用ADMIN_CMD()存储过程,可以为某些CLP命令提供SQL接口,请查阅手册: 使用ADMIN_CMD导入
You also have the option of reading the file, line by line, and inserting into your database. 您还可以选择逐行读取文件并将其插入数据库。 This will definitely be slower than any native import operation.
这肯定比任何本地导入操作都要慢。 Assuming your delimited file structure is, and the file is named
input.txt
: 假设您的分隔文件结构为,文件名为
input.txt
:
ORDER_ID^item^price
1^'bat'^50.00
2^'ball'^25.00
Code: 码:
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()
Play around with commit()
placement, you probably want to commit in batches to improve performance. 尝试一下
commit()
放置,您可能希望分批提交以提高性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.