?
Solved

Python SQL Query Results to CSV file

Posted on 2013-05-21
4
Medium Priority
?
4,553 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 25

Accepted Solution

by:
clockwatcher earned 2000 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: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering 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

Flask is a microframework for Python based on Werkzeug and Jinja 2. This requires you to have a good understanding of Python 2.7. Lets install Flask! To install Flask you can use a python repository for libraries tool called pip. Download this f…
Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
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 …
Suggested Courses

770 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