Skip to content

How to Connect to SQL Server database using Python, pyodbc

Last updated on December 26, 2022

In this post, we gonna use pyodbc a package to connect to the SQL server using Python. So let’s install the package using the pip package installer.

Here is the command to install

$ pip install  pyodbc

After installing the pyodbc package, you can use the following code snippet to connect to SQL Server.

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 the SQL server to which you have connected,

cursor.execute("select * from products")
row = cursor.fetchone()

while row:
    print(row)
    row = cursor.fetchone()

Here is a simple example code snippet to update a particular row

name = 'PHP Book'
category = 'books'
id = 1
cursor.execute("UPDATE products SET title = ?,  category = ? where id = ?", name, category, id)
cursor.commit()

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments