问题描述
我正在使用 python 库 IBM_DB,我可以用它建立连接并将表读入数据帧.从 Python 中的数据帧源写入 DB2 表(INSERT 查询)时出现问题.
I am using python library IBM_DB with which I am able to establish connection and read tables into dataframes.The problem comes when writing into a DB2 table (INSERT query) from a dataframe source in python.
下面是连接的示例代码,但有人可以帮助我如何将数据帧中的所有记录插入到 DB2 中的目标表中吗?
Below is sample code for connection but can someone help me how to insert all records from a dataframe into the target table in DB2 ?
import pandas as pd
import ibm_db
ibm_db_conn = ibm_db.connect("DATABASE="+"database_name"+";HOSTNAME="+"localhost"+";PORT="+"50000"+";PROTOCOL=TCPIP;UID="+"db2user"+";PWD="+"password@123"+";", "","")
import ibm_db_dbi
conn = ibm_db_dbi.Connection(ibm_db_conn)
df=pd.read_sql("SELECT * FROM SCHEMA1.TEST_TABLE",conn)
print df
如果给定带有硬编码值的 SQL 语法,我也可以手动插入记录:
I am also able to insert a record manually if given SQL syntax with hard coded values :
query = "INSERT INTO SCHEMA1.TEST_TABLE (Col1, Col2, Col3) VALUES('A', 'B', 0)"
print query
stmt = ibm_db.exec_immediate(ibm_db_conn, query)
print stmt
我无法实现的是从数据帧插入并将其附加到表中.我也试过 DATAFRAME.to_SQL() 但它出现以下错误:
What I am unable to achieve is to insert from a dataframe and append it to the table.I've tried DATAFRAME.to_SQL() as well but it errors out with the following :
df.to_sql(name='TEST_TABLE', con=conn, flavor=None, schema='SCHEMA1', if_exists='append', index=True, index_label=None, chunksize=None, dtype=None)
这个错误说:
pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ibm_db_dbi::ProgrammingError: SQLNumResultCols failed: [IBM][CLI Driver][DB2/LINUXX8664] SQL0204N "SCHEMA1.SQLITE_MASTER" is an undefined name. SQLSTATE=42704 SQLCODE=-204
推荐答案
您可以使用 ibm_db.execute_many()
将 Pandas 数据框写入 ibm db2.
You can write a pandas data frame into ibm db2 using ibm_db.execute_many()
.
subset = df[['col1','col2', 'col3']]
tuple_of_tuples = tuple([tuple(x) for x in subset.values])
sql = "INSERT INTO Schema.Table VALUES(?,?,?)"
cnn = ibm_db.connect("DATABASE=database;HOSTNAME=127.0.0.1;PORT=50000;PROTOCOL=TCPIP;UID=username;PWD=password;", "", "")
stmt = ibm_db.prepare(cnn, sql)
ibm_db.execute_many(stmt, tuple_of_tuples)
这篇关于从 python 数据帧插入到 DB2 表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!