Skip to content

Instantly share code, notes, and snippets.

@ZenithClown
Last active April 10, 2021 08:00
Show Gist options
  • Save ZenithClown/9700b120ec6cb1acb5ce7bdf4fe65dbf to your computer and use it in GitHub Desktop.
Save ZenithClown/9700b120ec6cb1acb5ce7bdf4fe65dbf to your computer and use it in GitHub Desktop.
Connecting to SQL Server using python-pyodbc
# -*- encoding: utf-8 -*-
"""Connecting to SQL Server using python3
Microsoft SQL Server is Proprietary to Microsoft, and connecting
to SQL Server using Python is explored in this code.
By default, connecting to SQL Driver requires installation of an
appropriate driver, and using the `pyodbc` module. More information
is available at
https://docs.microsoft.com/en-us/sql/sql-server/?view=sql-server-ver15
## Installing `pyodbc`
pip install pyodbc
## Windows Installation
Download the Windows Driver available in the Documentations, and you're
good to go!
## Ubuntu Based Installation
```bash
sudo su
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
apt-get install -y curl wget gnupg
curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
exit
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install -y msodbcsql17
# optional: for bcp and sqlcmd
sudo ACCEPT_EULA=Y apt-get install -y mssql-tools
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
source ~/.bashrc
# optional: for unixODBC development headers
sudo apt-get install -y unixodbc-dev
```
If `curl` is unavailable, then you can try with `wget` followed by `dpkg --install`.
"""
__author__ = "Debmalya Pramanik"
__author_email__ = "dPramanik.INSW@gmail.com"
__credits__ = {
"Felix" : {
"__meta__" : "Stack-Overflow User",
"question" : "Installing Microsoft ODBC Driver to Debian",
"link" : "https://superuser.com/questions/1355732"
},
"Microsoft Documentations" : "https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15"
}
__status__ = "production"
__version__ = "1.0-basic"
__docformat__ = "camelCasing"
__copyright__ = "Copyright (c) 2020 Debmalya Pramanik | Indian Institute of Technology (IIT), Dhanbad"
__affiliation__ = "Inspirigence Works Pvt. Ltd."
import pyodbc
import getpass
setConnectionString = lambda server, database, username, password : f"DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}"
def connect(connection_string : str) -> [pyodbc.Connection, pyodbc.Cursor]:
"""Connect to SQL Server and Returns the Connection and Cursor"""
_con = pyodbc.connect(connection_string)
_cur = _con.cursor()
return _con, _cur
def closeConnection(connection : pyodbc.Connection, cursor : pyodbc.Cursor) -> None:
"""Close the pyodbc Connection"""
cursor.close()
connection.close()
return None
if __name__ == "__main__":
# get connection details
server = input("Server Address: ")
username = input("Username : ")
password = getpass.getpass("Password : ")
database = input("Database Name : ")
con, cur = connect(setConnectionString(server, database, username, password))
# execute SQL Query for testing purpose
query = "SELECT * FROM Payments" # for demonstration only
# executes the query, and prints the result into console
cur.execute(query)
# return the data in JSON format
rows = [dict(
(cur.description[i][0], value) for i, value in enumerate(row)
) for row in cur.fetchall()]
rows = [row[0] for row in rows]
closeConnection(con, cur)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment