[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Python SQL Query Results to CSV file

Posted on 2013-05-21
4
Medium Priority
?
4,959 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

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

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

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…
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

649 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