-1

我将发布我的代码并在之后进行解释:

db = sqlite3.connect("Gene.sqlite")
cur = db.cursor()
cur.execute("SELECT * FROM Table")
for i in cur.fetchall():
    if i[0] == name:
    print '<br>' '<c><b>TYPE'':</b>' ' '+ i[1]+ '<br>'\
    '<b>DESCRIPTION:</b></c>' ' '+ i[2]
    break
else:
    print 'This name does no exist in the Database'

这是在 python 中,我正在创建一个 CGI 脚本,用户在其中输入一个名称,我的脚本进入该数据库,搜索名称并打印出该名称的行。我有一个数据库,其中包含一个名为 Table 的表,其中包含数千个名称,我只想让用户输入一个名称,并让它在表中搜索,并找到一个与输入匹配的名称,如果该名称存在,则打印必要的信息(如图所示)。但是,对于每个不匹配的名称,它会打印此名称不存在,直到找到匹配项,如果未找到匹配项,我只会收到数千条消息说“此名称不存在”。基本上,我希望它在不打印任何内容的情况下搜索表格,直到找到名称,如果找到名称,则打印出信息,如果不存在,则只打印一次“

4

4 回答 4

3

您需要使用WHERE clause

db = sqlite3.connect("Gene.sqlite")
cur = db.cursor()
looking_for = 'hello'
cur.execute("SELECT type,description FROM Table WHERE name = '%s'", (looking_for,))
for i in cur.fetchall():
    result = '<br><c><b>TYPE:</b> {}<br><b>DESCRIPTION:</b></c> {}'
    print result.format(*i)
else:
    print '{} does not exist in the Database'.format(looking_for)
于 2012-12-16T08:10:59.097 回答
0

As Burhan Khalid answered, you could do that inside SQL, which is preferable and faster. But just for completeness sake, if you like to move logic from SQL zone to Python zone, as you did, that should work too. I believe the problem in your code is that the name field is not the index-0 one. Try printing i[0], i[1], i[2] and check whether this is the case.

Now, referring to columns can be done also by field name, so you could change your code to:

if i["name"] == name:

without counting on an index, and thus have a more robust logic.

于 2012-12-16T09:12:12.863 回答
-1

我认为这个问题是一个空白问题。

尝试这个

for i in cur.fetchall():
  if i[0] == name:
    print '<br>' '<c><b>TYPE'':</b>' ' '+ i[1]+ '<br>'\
      '<b>DESCRIPTION:</b></c>' ' '+ i[2]
    break
else:
  print 'This name does no exist in the Database'

另外,您是否在虚线处缺少“+”?

于 2012-12-16T08:05:41.583 回答
-1

每个数据库都支持 SQL 'LIMIT' 关键字来限制结果集的大小。这是要走的路,而不是循环可能的大型结果集。所以你的方法被打破了。修复您的查询,而不是修补解决方法。当然除此之外:在您的查询中包含“名称”。

于 2012-12-16T08:08:01.150 回答