I am trying to loop through a large 8gb database with psycopg2 and python. I have followed the documentation and I'm getting an error. I am trying to loop through each line of the database without using .fetchall() because its just to big to fetch it all into memory. You can't use fetchone() because it will fetch each column individually.
Note that the first time through it will return a value, on the second time through it will give the error.
The documentation reads:
Note cursor objects are iterable, so, instead of calling explicitly fetchone() in a loop, the object itself can be used:
>>> cur.execute("SELECT * FROM test;")
>>> for record in cur:
... print record
...
(1, 100, "abc'def")
(2, None, 'dada')
(3, 42, 'bar')
My code reads:
statement = ("select source_ip,dest_ip,bytes,datetime from IPS")
cursor.execute(statement)
for sip,dip,bytes,datetime in cursor:
if sip in cidr:
ip = sip
in_bytes = bytes
out_bytes = 0
time = datetime
else:
ip = dip
out_bytes = bytes
in_bytes = 0
time = datetime
cursor.execute("INSERT INTO presum (ip, in_bytes, out_bytes, datetime) VALUES (%s,%s,%s,%s);", (ip, in_bytes, out_bytes, time,))
conn.commit()
print "writing to presum"
and i get the following error:
for sip,dip,bytes,datetime in cursor: psycopg2.ProgrammingError: no results to fetch