Python SQLite3循环用fetchone查找行

问题描述 投票:0回答:2

我的代码中有一个代码片段,需要在数据库中找到一个mac地址,然后打印一个语句来显示它在哪一行。我将使用该行号来更新该行中的timestamp列。

我的sqlite3 DB看起来像这样:

CREATE TABLE IF NOT EXISTS My_TABLENAME (mac_addr TEXT, timestamp TEXT, location TEXT, serialno TEXT)"

代码看起来像这样。

import sqlite3 as lite
con = lite.connect("database.db")
con.row_factory = lite.Row
cur = con.cursor()
cur.execute('''SELECT mac_addr, timestamp, (SELECT COUNT(*) FROM MY_TABLENAME AS t2 WHERE t2.mac_addr <= t1.mac_addr) AS i FROM My_TABLENAME AS t1 ORDER BY timestamp, mac_addr''')
_data = cur.fetchone()
if str(_data[0]) != '5c:f5:da:e0:dd:44':
   cur.fetchone()
else:
   print "Found the device in row", str(_data[2])

当我在python cli中运行代码时,我在执行第一个fetchone()之后打印_data变量时得到以下内容

>>> _data
(u'34:0a:ff:b2:75:78', u'1433940972.03946', 135)
>>> 

所以我可以看到当前在_data变量中的行是第135行(这显然会发生变化)。

但是当我运行代码片段时,我发布了uptop,我得到了以下输出,这让我觉得循环不起作用。难道我做错了什么?

>>> import sqlite3 as lite
>>> con = lite.connect("database.db")
>>> con.row_factory = lite.Row
>>> cur = con.cursor()
>>> cur.execute('''SELECT mac_addr, timestamp, (SELECT COUNT(*) FROM My_TABLENAME AS t2 WHERE t2.mac_addr <= t1.mac_addr) AS i FROM My_TABLENAME AS t1 ORDER BY timestamp, mac_addr''')
<sqlite3.Cursor object at 0x7ff99fc0a8f0>
>>> _data = cur.fetchone()
>>> if str(_data[0]) != '5c:f5:da:e0:dd:44':
...    cur.fetchone()
... else:
...    print "Found the device in row", str(_data[2])
... 
(u'18:83:31:61:83:8c', u'1433940974.39824', 74)
>>>

任何建议都会很棒。

python sqlite
2个回答
0
投票

谢谢。我设法将IF语句更改为For循环并以此方式获得成功。

虽然我认为WHERE语句从长远来看会更有效。我会试验一下然后看看。

谢谢


0
投票
cur.execute('''SELECT mac_addr, timestamp, 
                     (SELECT COUNT(*) FROM My_TABLENAME AS t2
                       WHERE t2.mac_addr <= t1.mac_addr) AS i 
                 FROM My_TABLENAME AS t1 WHERE mac_addr = ?
                ORDER BY timestamp, mac_addr''', '5c:f5:da:e0:dd:44')

它更快。

© www.soinside.com 2019 - 2024. All rights reserved.