【问题标题】:appending a parameter to sql script in python在python中将参数附加到sql脚本
【发布时间】:2021-06-30 19:55:18
【问题描述】:

假设python中的一个简单查询如下。 python 代码从用户那里读取一个“新城市”。问题是如何通过将城市列表(例如,'city1'、'city2'、'city3')附加到查询中的 where 子句来更新查询。

mycursor = mydb.cursor()

sql = "select * FROM my_table 

WHERE (city = 'Seattle') 
or (city = 'Portland')"

mycursor.execute(sql)

mydb.commit()

所需的 sql 脚本

mycursor = mydb.cursor()

sql = "select * FROM my_table 

WHERE (city = 'Seattle') 
or (city = 'Portland')
or (city =  'city1') 
or (city = 'city2)
or (city ='city3')"

mycursor.execute(sql)

mydb.commit()

【问题讨论】:

  • 你没有使用WHERE city IN ('Seattle', 'Portland', ...)有什么原因吗?

标签: python mysql


【解决方案1】:

使用city IN (...) 而不是多个city = 操作。然后您可以动态构建占位符列表并使用参数替换它们。

cities = ['Seattle', 'Portland', 'city1', 'city2', 'city3']
placeholders = ','.join(['%s']*len(cities))
sql = f'SELECT * FROM my_table WHERE city IN ({placeholders})'
mycursor.execute(sql, cities)

【讨论】:

    【解决方案2】:

    解决方案需要像这样进行字符串操作(假设您将输入输入到变量 newCity):

    mycursor = mydb.cursor()
    sql = "select * FROM my_table WHERE (city = 'Seattle') or (city = 'Portland')"
    
    #put in for loop for as long as ud like 
    newCity = input("insert new city")
    sql = sql + " or (city = \'" + newCity + "\')"
    
    mycursor.execute(sql)
    mydb.commit()
    

    【讨论】:

      猜你喜欢
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 2016-12-01
      • 2015-08-31
      • 2016-02-26
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多