Python Forum

Full Version: Output SQL to csv or xls file?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
Have a bit of code that runs a sql query - can't seem to get it to output to a .csv or an .xlsx file. Any help is appreciated

The window has several buttons, each of which should generate a report. The button label in this example is "Count of All Codes" - just trying to change the last line so that it writes to a file like "C:/mytestfile.csv"

if event =="Count of All Codes":
    connstring = 'DRIVER={SQL Server};SERVER=XXX;DATABASE=XXX;UID=XXX;PWD=XXX'
    SQLStr = "SELECT subsource_type_desc,  COUNT(*) AS 'num' FROM [TSCACS] GROUP BY subsource_type_desc order by num desc"
    conn = pyodbc.connect(connstring)
    cursor = conn.cursor()
    cursor.execute(SQLStr)
    for row in cursor:
        print(row)
Thanks again for any help.
Check out the csv module. It makes it very easy to write csv files.
Thank you, I have read through as much of the csv documentation as I can find, but I cannot get it to work. Literally every time I run it, I fix some syntax error, then get another one. It seems that the code I'm finding and trying is either outdated, wrong, or I'm just incapable of figuring out all of the syntax and structures required.

If you know of anything reasonably stable that you could point me to, I'd happily give it another shot.

Otherwise, if anybody else could give me a hand with the code I have above, I'd be most grateful.
Why don't you post some of the csv code you tried, and we'll help you fix it?
Thank you for getting back to me. This is probably my 20-25th try just to get sql results into a .csv, and unfortunately, I don't keep code after continuous failures (at some point I have to go back to the starting line and I delete everything I had done prior). So I'm sorry to say, I have no evidence of what I've worked on up to this point, only the base code that gets me to what I thought was like 95% of the way there.

But I understand that your goal is to help people learn, not do for them, so you can feel free to move on to other users who need help and delete this thread. The next time I attempt to do something in Python I'll keep the text file copies of my dry runs so I can be more aptly prepared for forum help requests.

Have a great day and thanks again for your time.