[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5916
  • Last Modified:

Python SQL Query Results to CSV file

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
sonofstimpy1
Asked:
sonofstimpy1
  • 2
1 Solution
 
clockwatcherCommented:
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
 
sonofstimpy1Author Commented:
On the query.dump

Can I fit in a select statement with some where clauses?
0
 
sonofstimpy1Author Commented:
That worked great, Clockwatcher. Thank you!
0
 
Paul JungCommented:
You are a life saver!!! THank you!!
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now