Solved

Python SQL Query Results to CSV file

Posted on 2013-05-21
4
3,631 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
ID: 39186390
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
ID: 39187289
On the query.dump

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

Author Closing Comment

by:sonofstimpy1
ID: 39188649
That worked great, Clockwatcher. Thank you!
0
 

Expert Comment

by:Paul Jung
ID: 41770774
You are a life saver!!! THank you!!
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Plenty of writing has gone on the web trying to compare Python with other competitive programming languages and vice versa. However, not much has been put into a wholistic perspective. This article should help you decide whether to adopt Python as a…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
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 …

861 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