我的代码中有一个片段,需要在数据库中找到一个mac地址,然后打印一个语句来显示它被找到的行。然后我将使用该行号来更新timestamp列在那一行。
我的sqlite3数据库看起来像这样:
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)
>>>
请提出任何建议。
答案 0 :(得分:0)
感谢。我设法将IF语句更改为For循环并以此方式获得成功。
虽然我认为WHERE语句从长远来看会更有效率。我会试验一下然后看看。
由于
答案 1 :(得分: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')
速度更快。