在sqlite3 LIKE查询中使用python字符串

时间:2012-11-29 18:39:47

标签: python sqlite cgi

感谢您提前提供任何帮助。我在Stackoverflow和Google上看到了这个问题的几个解决方案,但是在实现时似乎没有一个对我有用。我只是尝试将包含在变量中的python字符串传递给sqlite3 WHERE LIKE查询。没有任何错误,只是没有屏幕输出。以下是我尝试过的代码:

尝试1:     导入cgi     import sqlite3

#Get string/Clean string:
form = cgi.FieldStorage() 
term = form.getfirst('term', 'empty')
term = cgi.escape(term)

#Open DB Connection:
conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()

#Search and Print Results
print "\nResults from a LIKE query on %s:\n" % term
sql='SELECT * FROM myTable WHERE column LIKE %s'
args=['%'+term+'%']
cursor.execute(sql,args)
print cursor.fetchall()

Try2:     导入cgi     import sqlite3

#Get string/Clean string:
form = cgi.FieldStorage() 
term = form.getfirst('term', 'empty')
term = cgi.escape(term)

#Open DB Connection:
conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()

#Search and Print Results
print "\nResults from a LIKE query on %s:\n" % term
term = '%' + term + '%'
cursor.execute("SELECT * FROM table WHERE column LIKE ?", (term,) )
print cursor.fetchall()

如果我把LIKE'%http%'放到代码中,代码就可以工作,但总是会失败。 cgi与它有关吗?如果我只是将术语打印到屏幕上,则可以打印出来。

0 个答案:

没有答案