In this post, we gonna use pyodbc
package to connect to the SQL server using Python. So let’s install the package using pip package installer.
Here is the command to install
1 |
$ pip install pyodbc |
After installing the pyodbc
package, you can use the following code snippet to connect to SQL Server.
1 2 3 4 5 6 7 8 9 |
import pyodbc server = 'YourHostName' database = 'DatabaseName' username = 'ServeruserName' password = 'YourServerPassword' driver = '{ODBC Driver 17 for SQL Server}' cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server + ';PORT=1433;DATABASE='+database+';UID='+username+';PWD=' + password) cursor = cnxn.cursor() |
Here is the simple example code to fetch data from SQL server which you have connected,
1 2 3 4 5 6 |
cursor.execute("select * from products") row = cursor.fetchone() while row: print(row) row = cursor.fetchone() |
Here is the simple example code snippet to update a particular row,
1 2 3 4 5 |
name = 'PHP Book' category = 'books' id = 1 cursor.execute("UPDATE products SET title = ?, category = ? where id = ?", name, category, id) cursor.commit() |
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.