从 python 数据框插入 DB2 表

时间:2023-05-12
本文介绍了从 python 数据框插入 DB2 表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在使用 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 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:在 Python 中将 SQL 与 IBM_DB 连接器一起使用 下一篇:“import *"到底是什么?进口?

相关文章