It is possible to do this yes - I wonder if it will be useful to simply store the values in a text file: in general recover the desired data in the database and process them directly is better than Pear the same data from a text file, where we have no indexing tool, ways to search, etc...
It is very strange to me that you are having a "memory error" with records as simple as these - even millions of records should not exhaust the memory of a system with RAM in the gigabyte home.
Now, turning specifically to what you ask - the Python database connectors - all - implement beyond the fetchall
, the fetchmany
- which returns only the requested number of records.
So, one way to transfer a query to a local file (which I don’t consider useful - unless that’s all you want to do with the data) would be:
import csv
c = conn.cursor()
c.execute("SELECT latitude, longitude, gid FROM pontos")
with open("arquivo_destino.csv", "wt") as file_:
writer = csv.writer(file_)
writer.writerow(("latitude", "longitude"))
records = True
while records:
records = c.fetchmany(100)
writer.writerows(records)
...
The connection cursor itself can also be used as an iterator,
returning a query result at a time if it is used in a query - this way of using is better if you are consuming your data, rather than simply writing it to a local file:
c = conn.cursor()
c.execute("SELECT latitude, longitude, gid FROM pontos")
for record in c:
# do things with row result
(but I’ve seen bugle implementations of coenxions to the bank in which interacting the cursor that way was very slow - if that’s the case, better make a combination with fetchmany as well).
By your comment below, your error has nothing to do with the amount of data - include the error message that actually happens. S and the code has changed, it might be better to ask another question.
– jsbueno
In fact, there is no error, the system simply hangs. I already left the code running an entire night, I had to restart the computer and had not included any entries in the new database.
– Jessica Costa