简体   繁体   English

ibm_db_dbi同意DB2执行sql语句

[英]ibm_db_dbi connent to DB2 executing a sql statement

Python3.5 is normal, but Python2.7 raises this below error Python3.5正常,但是Python2.7引发以下错误

ibm_db_dbi.Error:ibm_db_dbi::Error : Error occurred during processing of statement ibm_db_dbi.Error:ibm_db_dbi :: Error:处理语句期间发生错误

Here is my code 这是我的代码

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

Basically, you are passing one-item lists instead of scalar values in your string interpolation with modulus operator, % . 基本上,您是在使用模运算符%字符串插值时传递单项列表而不是标量值。 Therefore, the length issue is raised which you can see by printing out concatenated SQL string which shows an invalid query with unclosed quotes: 因此,提出了长度问题,您可以通过打印出串联的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']'

Interestingly, as you point out, this does not fail in Python 3 but does in Python 2. To resolve, simply index first item or assign no brackets [] to obj and fw_ip that renders them a list. 有趣的是,正如您所指出的那样,这在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]))

However, in best practices, use parameters with params argument of cur.execute() which expects a sequence such as tuple or list but adjust SQL string with unquoted placemarkers, ? 但是,在最佳实践中,请使用带有cur.execute() params参数的参数,该参数需要一个诸如元组或列表之类的序列,但可以使用未加引号的地标来调整SQL字符串? :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM