我想要一个简单的 python 程序来提示用户输入标题并搜索 mySQL 数据库。我已经构建了数据库,但我不知道如何正确查询它。
import MySQLdb
servername = "localhost";
username = "username";
password = "password";
conn = MySQLdb.connect(user=username,host=servername, passwd=password, db=db)
cursor = conn.cursor()
user_input = raw_input("What do you want to watch?:")
query= ("SELECT * from videos where title LIKE %s")
cursor.execute(query,user_input)
如果我将查询硬编码为“where title LIKE '%HARDCODE%'”,那么它就可以正常工作。我认为解决方案非常简单,但我终究无法弄清楚。任何帮助深表感谢!我已经尝试了所有可以在网上找到的变体,但都无济于事。 我试过的其他一些:
query= ("SELECT * from videos where title LIKE CONCAT('%',%s,'%')")
cursor.execute(query,(user_input,))
query= ("SELECT * from videos where title LIKE (search)"
"VALUES (%s)", user_input)
...它们都不起作用。
错误似乎都围绕着我正确传递我的变量 user_input。
最佳答案
您可以像这样创建查询:
c.execute("SELECT * FROM videos WHERE title LIKE %s", ("%" + user_input + "%",))
关于python - 用户输入到 mySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36708125/