Home > Software design >  How to send in python params (which is string) into SQL question on DB2
How to send in python params (which is string) into SQL question on DB2

Time:11-08

I want to write function which receive parameter as string which should be used inside SQL statement for DB2 database. Then I need to take row by row and do smth in each loop step:

import ibm_db
conn_str = 'database=xxx;hostname=x.x.x.x;port=xxxx;protocol=TCPIP;UID=xxxxx;pwd=secret;'
ibm_db_conn = ibm_db.connect(conn_str,'','')

def question_to_db(tel : string):
    sql = "SELECT * from mper where mper.tel = ?"
    sql2 = ibm_db.prepare(ibm_db_conn, sql)
    ibm_db.bind_param(sql2, 1, tel, ibm_db.SQL_PARAM_INPUT, ibm_db.SQLCHAR)
    stmt = ibm_db.exec_immediate(ibm_db_conn, sql2)
    row = ibm_db.fetch_both(stmt)
    while row != False
        do_smth_with_row ....
        row = ibm_db.fetch_both(stmt)
    return(True)

After run of program I receive error:

stmt = ibm_db.exec_immediate(ibm_db_conn, sql2)
Exception: statement must be a string or unicode

I'm looking for any solution of my problem. I can't find any exmaples with string and fetching rows :(

Any one can help me ? Thanks in advance.

CodePudding user response:

Well, the Db2 Python API documentation has an example. The problem is that your are mixing different functions. You either

  • execute_immediate: A string is passed in to be executed once as SQL statement.
  • prepare and execute: You first prepare a string as SQL statement to be executed. When prepared, you can execute that statement once or many times.

Something like this should work:

sql_stmt = "SELECT * from mper where mper.tel = ?"
stmt = ibm_db.prepare(ibm_db_conn, sql_stmt)
ibm_db.bind_param(stmt, 1, tel)
try:
   ibm_db.execute(stmt)
except:
   print(ibm_db.stmt_errormsg())
  • Related