python - 用户输入到 mySQL 数据库

标签 python mysql database

我想要一个简单的 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/

相关文章:

javascript - Scrapy:通过Javascript获取内容集

mysql - 回滚过程插入

php - 如何在php中使用sql变量传递sql查询

mysql - 使用 order by 和 group by 连接表

python - 如何使用 PostgreSQL 在 Python 中理解和使用 asyncio?

Python:用CJKLIB将汉字转成拼音

php - 导出的数据库为空

python - Django 的受限数据库用户

python - 连接到 mercurial pretxncommit。并且不能导入请求模块?

mysql - SQL Left Join 但不希望左表中的所有记录