Skip to content Skip to sidebar Skip to footer

In Python, Display Output Of Sql Query As A Table, Just Like It Does In Sql

this seems like a basic function, but I'm new to Python so maybe I'm not googling this correctly. In Microsoft SQL Server, when you have a statement like SELECT top 100 * FROM dbo.

Solution 1:

It's more than 1 question, I'll try help you and give advice.

  1. I am running a connection to SQL through Python as such, and would like the output to look exactly the same as in SQL.

You are mixing SQL as language and formatted output of some interactive SQL tool. SQL itself does not have anything about "look" of data.

  1. Also note that neither of the Queries required me to know the column names or widths. My entire method here is attempting to eyeball the results of the Query and quickly check the data - I can't see that the Patient_IDs are loading properly if I don't know which column is patient_ids.

Correct. cursor.fetchall returns only data.

Field informations can be read from cursor.description.

Read more in PEP-O249

  1. how do i get 'data' to appear as a clean table with column names somewhere?

It depends how do you define "appear".

You want: text output, html page or maybe GUI?

  • For text output: you can read column names from cursor.description and print them before data.

  • If you want html/excel/pdf/other - find some library/framework suiting your taste.

  • If you want an interactive experience similar to SQL tools - I recommend to look on jupyter-notebook + pandas.

Something like:

pandas.read_sql_query(sql)

will give you "clean table" nothing worse than SQLDeveloper/SSMS/DBeaver/other gives.

Post a Comment for "In Python, Display Output Of Sql Query As A Table, Just Like It Does In Sql"