关于Python中使用SQL语句进行模糊查询

algorain

今天想写个脚本查一下数据库里的一些数据,但有些名称我只记得一些,便想到使用SQL语句中的模糊查询,正常的模糊查询应该是这样的

1
select * from tables where like %关键字%

但是Python对%会转义,总是出错,改了好多次,最后发现不用全部都写出来,写成下面这样就可以了

1
2
3
4
5
6
select_name = raw_input()
domain_str = "%" + select_name + "%"
sql = """select * from pass where site like %s """
result = cur.execute(sql, (domain_str))
for line in cur.fetchmany(result):
print line[1]

Python对中文各种报错,关于Python连接数据库和对数据的其他操作,以及报错处理,可以看我其他的文章

  • Title: 关于Python中使用SQL语句进行模糊查询
  • Author: algorain
  • Created at: 2017-02-11 21:22:14
  • Updated at: 2023-05-14 21:39:50
  • Link: http://www.rain1024.com/2017/02/11/python-article47/
  • License: This work is licensed under CC BY-NC-SA 4.0.
 Comments