python - python操作数据库报错

标签 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...

最佳答案

请注意,我没有太多 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

关于python - python操作数据库报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45459162/

相关文章:

Python Semaphore 似乎在 Google Colab 中不起作用

python - 在 mysql 中更新数千行的最快方法是什么

postgresql - 如何避免缓存计划不得更改结果类型错误?

javascript - 如何使用Node JS、Postgres和dust js在数据库中搜索数据

sql - 关于约束

python - 尝试 pip install pystan 时版本冲突 6 1.5.2 与 6>=1.6.0'

python - Django 提交无效表单时出错 (VariableDoesNotExist)

mysql - 更新字段值但也应用上限?

php - 迁移到 PHP 5.6 : Writing a MySQL wrapper

php - mysql仅当另一个字段为空或为空时才从行中删除