If I'm reading your code correctly, you're doing the following:
Querying database 1
Querying database 2
Writing to file 1 using query 1
Writing to file 2 using query 2
Also, it looks like your two queries and associated output files are completely independent of each other. In that case, I'd recommend doing the following:
Connect and query database 1
Write to file 1
Use undef on the variables related to database 1
Repeat above steps for database 2 and file 2
This will limit the amount of data in memory and free up memory once you're done with that data.