我正在编写一个脚本来查询本周内包含特定 url 的文章。我在插入 url 时遇到问题,试图使用 LIKE 过滤器检查某个 url。我尝试像对已发布的开始周和结束周那样进行插值,但它似乎与双插值混淆了。
澄清一下,脚本在查询的 %{http://foo.com/bar}%
部分出错
start_week = today - datetime.timedelta(today.weekday())
end_week = start_week + datetime.timedelta(7)
cursor = db.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("""SELECT * FROM table WHERE url LIKE '%{http://foo.com/bar}%'""", [start_week, end_week])
result = cursor.fetchall()
print len(result)
最佳答案
python 不喜欢括号,它会与嵌套插值混淆。我建议在字符串中添加 % 并将其插入到查询中。
bar = '%http://foo.com/bar%'
cursor = db.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("""SELECT * FROM table WHERE url LIKE %s""", [bar])
result = cursor.fetchall()
尽情享受吧!
关于python - 你如何在python中执行带有url的mysql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22022243/