2017-06-22 119 views
0

Python3.5是正常的,但Python2.7提出了下面这样的错误ibm_db_dbi connent到DB2执行SQL语句

ibm_db_dbi.Error:ibm_db_dbi::Error : Error occurred during processing of statement

这里是我的代码

import ibm_db_dbi 

def Conn_DB(): 
    global cur, conn 
    database = "test" 
    hostname = "127.0.0.1" 
    port = 50000 
    user = "test" 
    passwd = "test" 
    conn = ibm_db_dbi.connect(
    "DATABASE=%s;HOSTNAME=%s;PORT=%s;PROTOCOL=TCPIP;UID=%s;PWD=%s" % (database, hostname, port, user, passwd), "", 
    "") 
    conn.set_autocommit(True) 
    cur = conn.cursor() 
    return conn, cur 

def main(): 

    Conn_DB() 
    global cur 
    obj = ["1.1.1.1"] 
    fw_ip = ["3.3.3.3"] 
    cur.execute("select 1 from TEST where IP='%s' and firewall='%s'" % (obj,fw_ip)) 
    if cur.fetchone(): 
     print('hello, world') 

if __name__ == '__main__': 
main() 
+0

应该有有关该错误的更多详细信息,请添加它们。 –

+0

** bold **详细错误信息如下:** bold ** 文件“D:\ firewall_prase \ test.py”,第25行,主要在 cur.execute(“select 1 from TEST where IP ='% s'and firewall ='%s'“%(obj,fw_ip)) 文件”D:\ Python27 \ lib \ site-packages \ ibm_db-2.0.7-py2.7.egg \ ibm_db_dbi.py“在执行 self._prepare_helper(operation) 文件“D:\ Python27 \ lib \ site-packages \ ibm_db-2.0.7-py2.7.egg \ ibm_db_dbi.py”1205行,在_prepare_helper中 raise self.messages [ len(self.messages)-1] ibm_db_dbi.Error:ibm_db_dbi :: Error:处理语句期间发生错误 –

回答

0

基本上,你逝去的一个项目列表,而不是标量值在模数运算符%的字符串插值中。因此,长度问题提出,你可以看到打印出串联SQL字符串,它显示了未封闭的报价无效查询:

print("select 1 from TEST where IP='%s' and firewall='%s'" % (obj, fw_ip)) 

# select 1 from TEST where IP='['1.1.1.1']' and firewall='['3.3.3.3']' 

有趣的是,正如你指出,这并不在Python 3失败,但确实在Python 2.要解析,只需索引第一项或指定无括号[]objfw_ip将其呈现为列表。

obj = ["1.1.1.1"] 
fw_ip = ["3.3.3.3"] 

cur.execute("select 1 from TEST where IP='%s' and firewall='%s'" % (obj[0], fw_ip[0])) 

然而,在最佳实践,使用的参数与PARAMS说法cur.execute()这需要一个序列,例如元组或列表,但与未加引号的地点标记调整SQL字符串,?

cur.execute("select 1 from TEST where IP = ? and firewall = ?", (obj[0], fw_ip[0]))