Skip to content
Advertisement

Getting SQL Column to print in Python

I have a code that prints out a specific column from an SQL query table. It prints out fine however I would like it to be put into a file and I cannot think of how to do that.

Here is what I have:

#Connect to the database
testDBCon = sqlalchemy.create_engine('xxx')

#Choose what query to select a column from
query = "SELECT * FROM testDB.dbo.PIESData;"

#Choose to print out all rows and columns Selected
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
    df = pd.read_sql(query, testDBCon)

#Prints out only PartNumber and converts it to a string and prints all the values in every row
print( df[['PartNumber']].to_string() )

I was thinking of newfile.write( df[['PartNumber']].to_string() ) however that did not work.

Thank you for your help

Advertisement

Answer

Depending on what type of file, pandas supports many formats For a simple csv file you can do:

df.to_csv('file.csv', columns = ['PartNumber'], index = False)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement