Connect to SAP HANA Using Python
- How to install the SAP HANA client driver for Python
- How to install the client driver using a virtual environment (optional)
- How to connect to an instance of SAP HANA
- How to use environment variables to provide connection parameters
- A running SAP HANA database instance and credentials of a database user.
- Familiarity with Python.
- Step 1
Create a virtual environment to localize dependencies:ShellCopy
python -m venv venv
Activate the virtual environment:ShellCopy
After activating the virtual environment, you should see
(venv)in front of your Linux user in your bash shell. For example:
If you’re on Windows:cmdCopy
Create a dependency file and name it
hdbcli ### add other dependencies below ###
Install the dependencies:ShellCopy
pip install -r requirements.txt
The dependencies will be saved in your
You should see the following after installing the client:ShellCopy
Installing collected packages: hdbcli Successfully installed hdbcli-2.x.xxx
- Step 2
To establish a simple connection to SAP HANA, you need the following information:
- Database host
- Database port
- Database user
#connect.py #Import your dependencies from hdbcli import dbapi #Initialize your connection conn = dbapi.connect( address='<Database host>', port='<Database port>', user='<Database user>', password='<Password>' ) #If no errors, print connected print('connected') ### rest of your code here ###
You should never have database information directly in your code; you are only doing this for a connection test.
Run the file with:ShellCopy
If the connection information used is correct, you should see the following printed in your shell:ShellCopy
- Step 3
Now that you’ve successfully connected to the database, we need to take out connection parameters and credentials out of the source code. Having connection parameters directly in your source code is insecure, one option is to provide these parameters at runtime as environment variables instead.
Export your environment variables to your bash profile through your preferred method.BashCopy
export HOST="<Database Host>" export PORT="<Database Port>" export DB_USER="<Database User>" export DB_PW="<Password>"
We’ll use the
ospackage in Python to access these environment variables to connect.PythonCopy
from hdbcli import dbapi import os conn = dbapi.connect( address=os.environ['HOST'], port=os.environ['PORT'], user=os.environ['DB_USER'], password=os.environ['DB_PW'] ) print('connected') #test select from dummy table cursor = conn.cursor() cursor.execute("SELECT * FROM DUMMY") for result in cursor: print(result)
Test run the Python file again with:ShellCopy
Enter console output below to validate your connection.