【问题标题】:How do you use two user inputs from python in sql statement?如何在 sql 语句中使用来自 python 的两个用户输入?
【发布时间】:2020-06-11 08:23:38
【问题描述】:

这段 python 代码有问题,因为我不确定如何实现 sql 语句中获得的用户输入。

print("What two companies would you like to compare? ")
Company1 = input("What is the first compaany you would like? ")
Company2 = input("What is the second company you would like to add? ")
comData = [Company1, Company2]
carComData = (comData) 
cursor.execute("Select * from Cars where (Car_brand like?) or (Car_brand like?) order by car_id",(carComData))
cursor.execute(sql)
result = cursor.fetchall()
df = pd.DataFrame(result, columns=['Car_id', 'Car_Brand', 'Car_Model', 'Year', 'VIN', 'KmsTravelled', 'Price', 'Dealer_id'])
print (df)  '''

【问题讨论】:

  • 您到底遇到了什么麻烦?你用的是什么数据库?哪个司机?您在此处发布的示例有一些明显的错误,例如在cursor.execute(sql) 中使用了缺少的变量,以及整个print (df) ''',所以请提供minimal reproducible example
  • 每个数据库驱动程序都有(不幸的是)不同的绑定值语法。

标签: python sql python-3.x spyder


【解决方案1】:

试试这样的

cursor.execute("Select * from Cars where (Car_brand like %s) or (Car_brand like %s) order by car_id", (Company1, Company2))

你的问题是你有一个列表而不是一个元组中的参数。

【讨论】:

  • 感谢您的帮助。但是我不断收到“OperationalError:接近“%”:语法错误”。我知道这是您的代码的剪切和粘贴,但我不确定该去哪里。
  • 试试cursor.execute("Select * from Cars where Car_brand like ? or Car_brand like ? order by car_id", (Company1, Company2)),这可能会奏效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-08
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多