简体   繁体   中英

List of size 0 with 2 element after retrieving timestamp from sqlite3

con = sqlite3.connect(db_path,isolation_level=None, detect_types=sqlite3.PARSE_DECLTYPES)

cur.execute('SELECT TIMESTAMPSTART,COUNT from COUNTING order by ROWID DESC limit 1;')
print(cur.fetchall())
last_d=cur.fetchall()
print(type(last_d))
print(len(last_d))
print(last_d[0])

The result of this code is the following:

[(datetime.datetime(2019, 4, 8, 21, 49, 5, 675964), 2)]
<type 'list'>
0
Traceback (most recent call last):
  File "avg.py", line 70, in <module>
    stream.statuses.filter(track='bitcoin')
  File "/usr/lib/python2.7/site-packages/twython/streaming/types.py", line 67, in filter
    self.streamer._request(url, 'POST', params=params)
  File "/usr/lib/python2.7/site-packages/twython/streaming/api.py", line 154, in _request
    if self.on_success(data):  # pragma: no cover
  File "avg.py", line 59, in on_success
    update_counter()
  File "avg.py", line 38, in update_counter
    print(last_d[0])
IndexError: list index out of range

My database looks like this:

CREATE TABLE COUNTING(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
COUNT INT NOT NULL,
KEYWORD TEXT NOT NULL,
TIMESTAMPSTART TIMESTAMP NOT NULL,
TYPE TEXT NOT NULL
);

So why does it says the size of the list is 0 eventhough when I print it it has 2 elements? I'm just trying to retrieve my timestamp from the db

That's because you are returning no results. Pay attention to what your code does below. You have:

print(cur.fetchall())
last_d=cur.fetchall()

The print statement fetches all the rows leaving behind no rows for you to actually set the last_d variable to. As per here , An empty list is returned when no rows are available . Your print function consumes all the rows leaving none for the actual variable to store hence why it returns that it has a length 0 . Remove the print statement and see what happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM