Python Forum
[PYTHON EXPORT SQL TO .txt file]
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PYTHON EXPORT SQL TO .txt file]
#1
I would like to export my sql server query into a txt file.


import PYODBC

 

db = pyodbc.connect("Driver={SQL Server Native Client 11.0};"

                        "Server=server_name;"

                        "Database=table_name;"

                        "Trusted_connection=yes;")

cur= db.cursor()

sql = """SELECT TOP 5 * FROM Table"""

file= open("C:\\Users\\PYTHONDUDE\\Documents\\PYTHON_SCRIPTS\.test.txt", "w")

cur.execute(sql)

for row in cursor:

   print>>file, row[0]   -----  My error happens here using python 3.6

file.close()
Reply
#2
in python3 print is function. to redirect the the output to something else, instead to stdout use file argument
also it's good idea not to use builtin functions as variable names (file is builtin function in python2)
Reply
#3
can you please elaborate with pseudo code
Reply
#4
with pyodbc.connect("Driver={SQL Server Native Client 11.0};"
 
                        "Server=server_name;"
 
                        "Database=table_name;"
 
                        "Trusted_connection=yes;") as db:
 
    cur = db.cursor()
    sql = """SELECT TOP 5 * FROM Table"""
    cur.execute(sql)
    with open("C:/Users/PYTHONDUDE/Documents/PYTHON_SCRIPTS/.test.txt", "w", newline='') as f:
        for row in cur:
            print(row[0], file=f)
NB - not tested, but should work
Reply
#5
THANK YOU SO MUCH

final question
the print(row[0], file=f) only prints out 1 column (ID) , however my sql statement has over 10 cloumns, (ID, NAME, DATE , COUNTRY, STATE, .....) how can i modify to capture all data inmy sql.
AGAIN THANKS IN ADVANCE
Reply
#6
How would you print every column out, if it wasn't a file?
What is a row?
What is a row[0]?
Reply
#7
it prints just ID because of row[0], i.e. that is the first element in row

import csv
with pyodbc.connect("Driver={SQL Server Native Client 11.0};"
 
                        "Server=server_name;"
 
                        "Database=table_name;"
 
                        "Trusted_connection=yes;") as db:
 
    cur = db.cursor()
    sql = """SELECT TOP 5 * FROM Table"""
    cur.execute(sql)
    with open("C:/Users/PYTHONDUDE/Documents/PYTHON_SCRIPTS/.test.txt", "w", newline='') as f:
        wrtr = csv.writer(f)
        for row in cur:
            wrtr.writerow(row)
        #wrtr.writerows(cur.fetchall())
better to use csv module
you can replace the for row block with the last line
Reply
#8
for my knowledge why is it that i cant write all rows to my .txt file
the csv code returns an error wrtr.write(row) Attributerror: '_csv.writer' object has no attribute to write.

I updated the code to wrtr.writerow() the csv file was created but no data added to file
i also tried wrtr.writerow([ID, NAME, ADDRESS, DATE]) nothing written to file
Reply
#9
please, post your code. if the previous code worked row is tuple as expected. it should work
Reply
#10
(Feb-21-2018, 04:56 PM)nilamo Wrote: How would you print every column out, if it wasn't a file?
What is a row?
What is a row[0]?

You've gotten this far, I really do think you can solve this yourself if you take a step back and think about what you're doing.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Export Python output to Excel skyline1397 1 2,045 Jun-26-2022, 05:10 AM
Last Post: skyline1397
  How to keep columns header on excel without change after export data to excel file? ahmedbarbary 0 1,164 May-03-2022, 05:46 PM
Last Post: ahmedbarbary
  Yahoo_fin question: how does one export all stock tickers to a csv file detlefschmitt 9 8,778 Feb-12-2021, 07:46 AM
Last Post: detlefschmitt
  How to export from Python to Excel? jpy 4 6,371 Dec-23-2020, 03:26 PM
Last Post: jpy
  Skeleton file export error Python Code pepapoha 4 3,498 Nov-17-2020, 02:06 AM
Last Post: pepapoha
  Python Export Question Below samlee916 1 1,575 Jul-07-2020, 12:22 PM
Last Post: Larz60+
  CGI in python, problem with pandas, plotly.express and export html HK2432 0 2,132 Jan-19-2020, 01:30 PM
Last Post: HK2432
  export file and display cmd prompt same time jacklee26 1 2,031 Jul-24-2019, 05:15 AM
Last Post: Larz60+
  python export to csv writes extra line between rows jahjahcity 4 10,363 Jul-25-2018, 01:36 AM
Last Post: jahjahcity
  Need help to open PDF file and Export to text file ratna_ain 3 7,065 Oct-10-2017, 01:44 AM
Last Post: ratna_ain

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020