Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python/sqlite3中通过变量在一个表中的两列(或更多列)中执行搜索_Python_Sqlite - Fatal编程技术网

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

如何在python/sqlite3中通过变量在一个表中的两列(或更多列)中执行搜索,python,sqlite,Python,Sqlite,大家好。潜伏在这里是一个很大的帮助-提前感谢。 我要做的是接受用户的输入,然后在“mytable”表的“type”和“count”列中搜索与用户输入匹配的任何内容 这是我的密码: 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 =

大家好。潜伏在这里是一个很大的帮助-提前感谢。 我要做的是接受用户的输入,然后在“mytable”表的“type”和“count”列中搜索与用户输入匹配的任何内容

这是我的密码:

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打扮得更加友好(并且更接近python 3支持,尽管原始输入不是python 3的本机输入)。从那以后,你应该能够扩展

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

含糖的你需要花一点时间来理解你的代码。事实上,我刚刚发现(陷入)了另一种写的方法:cur.execute(“从mytable中选择*type LIKE?或count LIKE?”,(vart,vart))也可以工作。非常感谢。当搜索字符串包含单引号时,这会爆炸。是的,您需要更高级的格式语法来保护引号。Good warning.cgseller-您能指导我讨论一下您对.format()的使用以及如何正确使用它吗?我似乎找不到任何合适的方法。python文档是很好的参考。format是一个字符串方法。我认为这个PEP文档很好地涵盖了格式:当我将cur.execute行更改为:cur.execute(“从mytable中选择*类型,如(?)或计数,如(?),[vart])时,我得到以下错误:sqlite3.ProgrammingError:提供的绑定数量不正确。当前语句使用2,并且提供了1。如果我随后添加第二个[vart]如下:cur.execute(“从mytable中选择*类型,如(?)或计数,如(?),[vart],[vart]),则我会得到以下错误:TypeError:函数最多接受2个参数(给定3个),在这两种类型的查询之前运行一次,结果类似。参数需要包含在一个列表中;我已经更新了我的答案来说明这一点。