Is that a question?
Anyways, where is it that you are facing a problem? Is it reading from the database or writing to a CSV file?
Since database access is fairly normal, i assume you would know that.
This FAQ entry will give you the details of how to read/write CSV files.