python操作数据库错误

时间:2017-08-02 11:07:37

标签: python mysql postgresql python-3.x

我使用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...

1 个答案:

答案 0 :(得分: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