【问题标题】:The python operation database errorpython操作数据库报错
【发布时间】:2017-08-02 11:07:36
【问题描述】:

我用python操作postgresql数据库,执行sql,把引号去掉,导致查询失败,如何避免?

def build_sql(self,table_name,keys,condition):
    print(condition)
    # condition = {
    #     "os":["Linux","Windows"],
    #     "client_type":["ordinary"],
    #     "client_status":'1',
    #     "offset":"1",
    #     "limit":"8"
    # }
    sql_header = "SELECT %s FROM %s" % (keys,table_name)
    sql_condition = []
    sql_range = []
    sql_sort = []
    sql_orederby = []
    for key in condition:
        if isinstance(condition[key],list):
            sql_condition.append(key+" in ("+",".join(condition[key])+")")
        elif key == 'limit' or key == 'offset':
            sql_range.append(key + " " + condition[key])
        else:
            sql_condition.append(key + " = " + condition[key])
    print(sql_condition)
    print(sql_range)
    sql_condition = [str(i) for i in sql_condition]
    if not sql_condition == []:
        sql_condition = " where " + " and ".join(sql_condition) + " "
    sql = sql_header + sql_condition + " ".join(sql_range)
    return sql

错误:

MySQL Error Code : column "winxp" does not exist
LINE 1: ...T * FROM ksc_client_info where base_client_os in (WinXP) and...

【问题讨论】:

  • 如果它仅用于 MySQL,请不要用 postgresql 标记它(并且错误提示)

标签: python mysql postgresql python-3.x


【解决方案1】:

请注意,我没有太多 Python 经验,但基本上您在该序列中没有单引号,因此您需要在将其传递给函数之前添加这些单引号,或者例如在 join() 期间添加这些单引号,如下所示:

sql_condition.append(key+" in ("+"'{0}'".format("','".join(condition[key]))+")")

您可以在这些问题中看到其他解决方案:

Join a list of strings in python and wrap each string in quotation marks

Add quotes to every list elements

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-06
    • 2016-09-14
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多