避免在 psycopg2 中将整数作为参数传递的 Python SQL 语句中的类型错误

问题描述 投票:0回答:1

当我将参数 invoke_id 作为整数传递时,使用 psycopg2 库会遇到此特定错误

def check_invitations(self, invite_id=2):
    try:
        cur = self.db_cursor
        cur.execute("""
            select id from invitations where deleted_at is null and accepted_at is null and rejected_at is null and id = %s
        """, invite_id) 
        return cur.fetchall()       
    except Exception as e:
        print('Error in check_invitations: %s' % e) 
Error in check_invitations: 'int' object does not support indexing

但是当我将 inform_id 转换为字符串时,该命令执行并返回 fetchall():

def check_invitations(self, invite_id=2):
    try:
        invite_id = str(invite_id)
        cur = self.db_cursor
        cur.execute("""
            select id from invitations where deleted_at is null and accepted_at is null and rejected_at is null and id = %s
        """, invite_id) 
        return cur.fetchall()       
    except Exception as e:
        print('Error in check_invitations: %s' % e) 

要获取以整数形式执行 inform_id 的命令,我必须在元组中传递具有一个值的 int 值:

def check_invitations(self, invite_id=2):
    try:
        cur = self.db_cursor
        cur.execute("""
            select id from invitations where deleted_at is null and accepted_at is null and rejected_at is null and id = %s
        """, (invite_id,))
        return cur.fetchall()       
    except Exception as e:
        print('Error in check_invitations: %s' % e)  

具体来说,我的问题是为什么我必须在元组内传递整数,而可以直接传递字符串?我可以记下它并立即执行,但我试图理解为什么? “‘int’对象不支持索引”导致了这种情况(不是真正的问题)。

python psycopg2
1个回答
0
投票

感谢@snakecharmerb、@Marijn 和@AdrianKlaver - 这里真正更可靠的解决方案是始终将参数作为元组内的项目传递。例如,只有当字符串的长度== 1时,直接传递字符串才有效。如果字符串较长,则执行将不起作用,因为现在字符串的序列大于1。例如:

def check_invitations(self, invite_id=22):
    try:
        invite_id = str(invite_id)
        cur = self.db_cursor
        cur.execute("""
            select id from invitations where deleted_at is null and accepted_at is null and rejected_at is null and id = %s
        """, invite_id)
        return cur.fetchall()       
    except Exception as e:
        print('Error in check_invitations: %s' % e) 

返回此异常:

Error in check_invitations: not all arguments converted during string formatting

这里更好的解决方案是将所有参数传递到一个元组中。

def check_invitations(self, invite_id=22):
    try:
        invite_id = str(invite_id)
        cur = self.db_cursor
        cur.execute("""
            select id from invitations where deleted_at is null and accepted_at is null and rejected_at is null and id = %s
        """, (invite_id,))
        return cur.fetchall()       
    except Exception as e:
        print('Error in check_invitations: %s' % e) 

包含一项的元组需要尾随逗号以将变量标识为元组。

© www.soinside.com 2019 - 2024. All rights reserved.