How to connect Python and SQL Server – Part 2

Hey Guys,

In my first blog post about Python and SQL Server, I gave a very short introduction in how to actually connect and execute a simple query. Today I want to extend a bit on using Python and SQL Server.

As I described in the end of the previous post the ideal scenario is that you inherit the database connection from a single file and then use it whenever and anywhere you want. This makes your code to look cleaner and eliminate redundant work in case you need to change credentials or something else. For that I will show to you how to do it.

The first thing that I did was removing the extra code in the SQLConn.py file and only kept the database connection and create a class for it. So, in my other files that I need to inherit the connection I just do it for the connection class.

image

After that, we create a new Python file that we can call it Queries.py and then what we need to do is inherit the connection from the SQLConn.py. To do that, the very first thing you need to include is the below code.

from SQLConn import connection

As you see it, I will only use it from SQLConn the connection class or it could be also a function.

image

from SQLConn import connection

cursor = connection.conn.cursor()

cursor.execute("select * from sys.database_files")
for row in cursor.fetchall():
    print(row)

And this is our result. I just made a short print screen of the result.

image

Instead returning a list of values you can print the exact value in each row. You just need to modify a bit your print statement to something like that.

image

from SQLConn import connection

cursor = connection.conn.cursor()

cursor.execute("select * from sys.database_files")
for row in cursor.fetchall():
    print(row.name + " - " + row.physical_name)

The results would look like this.

image

I hope you liked the tip shared and if you have any feedbacks to share, please feel free to do so!

Regards,
Marcos Freccia

Advertisements

About Marcos Freccia

MVP em SQL Server (Data Plataform) , especialista em SQL Server, e atualmente trabalhando com Microsoft Azure!

Posted on August 2, 2017, in Python, SQL Server, SQL Server 2016, VirtualPass and tagged , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: