Solved

Python SQL Query Results to CSV file

Posted on 2013-05-21
4
3,025 Views
Last Modified: 2016-08-25
I'm doing a SQL query on MSSQL and I want those results written to a CSV file.

I've found numerous examples of the other way around, but I need the results to go into a CSV and it has to be done using Python.

Please help!
0
Comment
Question by:sonofstimpy1
  • 2
4 Comments
 
LVL 25

Accepted Solution

by:
clockwatcher earned 500 total points
Comment Utility
Here you go.
import pyodbc
import csv

class ODBCtoCSV(object):

    def __init__(self, connect='Driver={SQL Server};Server=SomeServer;Database=SomeDB;UID=SomeUser;PWD=SomePassword'):
        self.connect_string = connect

    def dump(self, sql, filename, include_headers=True):
        f = csv.writer(file(filename, 'wb'))

        cnxn = pyodbc.connect(self.connect_string)
        c = cnxn.cursor()
        c.execute(sql)

        if include_headers:
            f.writerow([d[0] for d in c.description])

        f.writerows(c.fetchall())
            
if __name__ == '__main__':
    
    query = ODBCtoCSV()
    query.dump("select * from SomeTable", "output.csv")

Open in new window

0
 

Author Comment

by:sonofstimpy1
Comment Utility
On the query.dump

Can I fit in a select statement with some where clauses?
0
 

Author Closing Comment

by:sonofstimpy1
Comment Utility
That worked great, Clockwatcher. Thank you!
0
 

Expert Comment

by:Paul Jung
Comment Utility
You are a life saver!!! THank you!!
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

This article will show the steps for installing Python on Ubuntu Operating System. I have created a virtual machine with Ubuntu Operating system 8.10 and this installing process also works with upgraded version of Ubuntu OS. For installing Py…
Strings in Python are the set of characters that, once defined, cannot be changed by any other method like replace. Even if we use the replace method it still does not modify the original string that we use, but just copies the string and then modif…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now