我的项目当前正在使用pypyodbc
Python库连接到DB2数据库,我的源是MS SQL服务器,我需要从中读取数据并将数据加载到DB2表中。数据量为一百万行,我正在尝试使用executemany()
方法在一次执行中加载50条记录,但我不断收到错误消息:
数据必须在列表,元组或行中
我确实使用了list
函数来转换我的光标结果,但仍然无法正常工作。结果集中的数据格式为[(record1),(record2)]
。代码段如下:
也尝试过类型转换sql结果集元组
# use pypyodbc to establish a connection - db2_conn.
cur = db2_conn.cursor()
cur.execute('...a query with 10 columns...')
result = cur.fetchmany(50)
insert_query = 'insert into db2_table (col1,col2,col3,...) values (?,?,?,..)'
cur.executemany(insert_query, list(result))
cur.commit()
该代码看起来不错-请发布失败的确切代码。我用Db2作为源和目标测试了以下内容:
db2 "create table odbc_test(c1 int, c2 varchar(10))"
db2 "create table odbc_test_sorurce(c1 int, c2 varchar(10))"
db2 "insert into odbc_test_sorurce
with
cte(c1)
as
(select
1
from
sysibm.sysdummy1
union all
select
c1 + 1
from
cte
where c1 < 1000) select c1, 'row' || c1 from cte"
import pyodbc
cnx = pyodbc.connect("DRIVER={DB2};HOSTNAME=localhost;DATABASE=sample;UID=xxxx;PWD=xxxxx;PROTOCOL=TCPIP;PORT=60115")
cnx.autocommit = False
cur = cnx.cursor()
cur.execute('select c1, c2 from odbc_test_sorurce')
result = cur.fetchmany(50)
In [16]: result
Out[16]:
[(1, 'row1'),
(2, 'row2'),
(3, 'row3'),
(4, 'row4'),
(5, 'row5'),
(6, 'row6'),
(7, 'row7'),
...
In [17]: type(result)
Out[17]: list
cur.executemany("insert into odbc_test(c1, c2) values (?,?)", result)
cnx.commit()