Using SQL with IBM_DB connector in Python

一个人想着一个人 提交于 2019-12-12 16:34:15

问题


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.


回答1:


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()


来源:https://stackoverflow.com/questions/50478410/using-sql-with-ibm-db-connector-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!