我有这个Python代码:
def get_employees(conditions, fields):
cursor.execute("SELECT employeeID FROM employees WHERE name=%s, budget=%s,
%year=%s,(some of conditions))
如果我设置的条件不是所有参数等,只有名称和年份,有没有办法获得employeeID
?
答案 0 :(得分:0)
如果conditions
是字典,则可以构造查询字符串:
def get_employees(conditions):
query = 'select employeeid from employees'
if conditions:
query += ' where ' + ' and '.join(key + ' = %s' for key in conditions.keys())
cursor.execute(query, conditions.values())
(我应该注意,在这里我假设conditions
没有用户提供的密钥。如果有用户提供的密钥,这肯定容易受到SQL注入。)
答案 1 :(得分:0)
通常是通过动态sql构建完成的,如下所示:
sql = "SELECT employeeID FROM employees WHERE 1=1";
if condition has name
sql += " and name='" .escape(name) . "'"
if condition has somefield
sql += " and somefield='" .escape(somefield) . "'"
etc
execute final sql