python怎么和sql一起用_在Python中将SQL与IBM_DB连接器一起使用

Has anyone used the ibm_db package with IBM's Python for PASE to update Db2 files on IBM i (formerly AS/400)?

I want to use Python scripts (from QSH) to update the Db2 database. My purpose is to populate values at runtime and update the fields of Db2 files. It works with static (hardcoded) values, but not dynamic ones.

Here is what I am trying, but it is not working:

import ibm_db

c1 = ibm_db.connect('*LOCAL','userid','password')

sql = """INSERT INTO TEMPLIB.TEMPPF (TYPE, DRPARTY, CRPARTY,

AMOUNT,ACNUM, DESCRIPT)

VALUES('%s', '%s', '%s', '%s', '%s', '%s'),

%(self.type, self.debitparty, self.creditparty, self.amount,

self.craccountnumber, self.description) with NC

"""

stmt = ibm_db.exec_immediate(c1, sql )

self.type, self.debitparty, etc. are Python instance variables and have values.

TYPE, DRPARTY, CRPARTY, etc. are fields of TEMPPF.

Something simpler like populating the 'sql' variable as below works:

sql = "select * from TEMPLIB.TEMPPF"

So somewhere I am not making the INSERT format correctly. Does anyone know the format please? I tried a couple of formats available on the Internet, but they are not compatible with Python, or they are not good examples.

解决方案

First, your concatenation of strings with the modulus operator is not correct as %(vars) needs to reside outside the string intended to be formatted.

Second, you should be using SQL parameterization (an industry standard in any database, not just DB2) and not string interpolation of data and query statement. You can do so using the ibm_db_dbi module to pass parameters in the cursor execute call:

import ibm_db

import ibm_db_dbi # ADD DBI LAYER

db = ibm_db.connect('*LOCAL','userid','password')

# ADD FOR PYTHON STANDARD DB-API PROPERTIES (I.E., CURSOR)

conn = ibm_db_dbi.Connection(db)

cur = conn.cursor()

# PREPARED STATEMENT (WITH PLACEHOLDERS)

sql = """INSERT INTO TEMPLIB.TEMPPF (TYPE, DRPARTY, CRPARTY,

AMOUNT, ACNUM, DESCRIPT)

VALUES(?, ?, ?, ?, ?, ?)

with NC

"""

# EXECUTE ACTION QUERY BINDING PARAMS

cur.execute(sql, (self.type, self.debitparty, self.creditparty, self.amount,

self.craccountnumber, self.description))

cur.close()

conn.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值