SQL 语句与插入数据库的值冲突

SQL statement clashes with values being inserted into database

由于正在插入 PostgreSQL 数据库的数据中存在“ '”,因此发生错误。错误如下:

psycopg2.ProgrammingError: syntax error at or near "S" LINE 1: ...ice_type) VALUES('7055598', 'CHEE KONG POI', 'HEE'S ENGINEER...

有办法解决这个问题吗?当前代码如下:

def store(license_number, individual_name, corporate_name, reg_address, email_address, land_line, hand_phone_line, work_type):
    statement = (
        "INSERT INTO service_reviews_serviceprovider" \
        " (license_number, individual_name, corporate_name, reg_address, email_address, land_line, hand_phone_line, service_type)" \
        " VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', 'electrician');"
    ).format(license_number, individual_name, corporate_name, reg_address, email_address, land_line, hand_phone_line)

    print(statement)
    cur.execute(statement)
    cur.connection.commit()
    return None

这是您在创建 SQL 语句时不使用字符串替换的原因之一。改为使用参数:

statement = (   
    "INSERT INTO service_reviews_serviceprovider" 
    " (license_number, individual_name, corporate_name, reg_address, email_address, land_line, hand_phone_line, service_type)"
    " VALUES(%s, %s, %s, %s, %s, %s, %s, 'electrician');"
)

cur.execute(
    statement, (license_number, individual_name, corporate_name, reg_address, email_address, land_line, hand_phone_line)
)

请注意,这会将整个参数集作为单个元组参数发送到数据库 api,数据库会根据需要进行引用。

除了解决您的问题外,这还可以防止 SQL 注入,这是您应该 始终 这样做的主要原因。

使用多行字符串"""。使用 cursor.execute 将参数传递给查询。在将要插入的值传递给 cursor.execute 之前将其转换为 tuple 以避免混乱的字符串构建和难以阅读的代码。

def store (
    license_number, individual_name, corporate_name, reg_address,
    email_address, land_line, hand_phone_line, work_type
):
    t = (
        license_number, individual_name, corporate_name, reg_address,
        email_address, land_line, hand_phone_line, 'electrician'
    )
    statement = """
        insert into service_reviews_serviceprovider (
            license_number, individual_name, corporate_name, reg_address,
            email_address, land_line, hand_phone_line, service_type
        ) values %s
    ;"""

    print cur.mogrify(statement, (t,))
    cur.execute(statement, (t,))
    cur.connection.commit()
    return None