How to connect Python and SQL Server – Part 2
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.
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.
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.
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.
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.
I hope you liked the tip shared and if you have any feedbacks to share, please feel free to do so!
Posted on August 2, 2017, in Python, SQL Server, SQL Server 2016, VirtualPass and tagged berlin, execute queries in python, Execute T-SQL from Python, How to Connect in SQL Server from Python, python and sql server, sql server berlin, SQL Server consultant Berlin. Bookmark the permalink. Leave a comment.