簡體   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