繁体   English   中英

如何通过python / sqlite3中的变量在一个表中的两列(或更多列)中执行搜索

[英]How to perform search in two (or more) columns in one table by variable in python/sqlite3

大家好。 在这里潜伏着很大的帮助-预先感谢。 我想做的是接受用户的输入,然后在“ mytable”表的“类型”和“计数”列中搜索与用户输入匹配的任何内容。

这是我的代码:

import sys
import sqlite3 as lite

for arg in sys.argv:
    print arg

var = raw_input("What are you looking for: ")
print "Standby; looking for : ", var
vart = '%'+var+'%'  # to add wildcards to the var string

con = lite.connect('test.db')

print 
print "Ok. Here's what I found."
print

with con:
    cur=con.cursor()
    cur.execute( "SELECT * FROM mytable" )
#   cur.execute( "SELECT * FROM mytable WHERE type LIKE ( ? )", [vart]) # this actually works - but only searches type column
#   cur.execute( "SELECT * FROM mytable WHERE type LIKE ( ? ) OR WHERE count like ( ? )", [vart], [vart] ) fails
#   cur.execute( "SELECT * FROM mytable WHERE type LIKE ( ? ) UNION ALL SELECT * FROM mytable WHERE count LIKE ( ?)", [vart], [vart])

    rows = cur.fetchall()
    # now row has each line to deal with
    #print len(rows)    #prints the number of lines in the db
    for row in rows:
        #print len(row) # prints the number of items in the list
        # if var in row[0]... then print
        mstr=row[0]
        print mstr.encode('ascii'), row[1]

这是微不足道的数据库:

type : count
fox|23
dog|34
cat|99
bird|123
rat|201
mouse|23
hedgehog|44
gnu|666

我仅在一个列中搜索了输入字符串就成功了,但是当我尝试同时创建两个列时,它失败了。 必须有一种使用sqlite3函数而不依赖python函数的方法。

一个有效的非嵌套SQL SELECT语句只有一个WHERE语句。 同样,如果你传递多个参数到sqlite的光标,它们必须包含在一个单一的列表。 您的代码的正确语法为:

cur.execute('SELECT * FROM mytable WHERE type LIKE ( ? ) OR count like ( ? )', [vart, vart])

只是进行了一点语法修复,我将您的python简化为对pep8更友好(并且更接近python3支持,尽管raw_input在python3中不是本机)。 由此,您应该可以扩展...。

import sys
import sqlite3 as lite
'''
made your code more pep8 python like
note comments in python are reserved for
why not what..e.g. code is self descriptive
of what, but why is what is important
'''

print('{}'.format(sys.argv))  # debug

var = raw_input("What are you looking for: ")
print("Standby; looking for :{}".format(var))
vart = '%{}%'.format(var)

con = lite.connect('test.db')

print("\nOk. Here's what I found.\n")

with con:
    cur = con.cursor()
    sql_query = 'SELECT * FROM mytable WHERE type LIKE ? or count LIKE ?'
    cur.execute(sql_query, ['%{0}%'.format(var), '%{0}%'.format(var)])

    try:
        rows = cur.fetchall()
    except Exception as err:
        print(err)
    for row in rows:
        mstr = row[0]
        print('Found: {} : {}'.format(mstr.encode('ascii'), row[1]))

输出示例

host-wifi:java user$ python /tmp/p.py
['/tmp/p.py']
What are you looking for: 99
Standby; looking for :99

Ok. Here's what I found.

Found: cat : 99
host-wifi:java user$ python /tmp/p.py
['/tmp/p.py']
What are you looking for: 3
Standby; looking for :3

Ok. Here's what I found.

Found: fox : 23
Found: dog : 34
Found: bird : 123

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM