Connect SAP HANA Database using Python Code
If you are a Python programmer and require to connect to SAP HANA databases to query and read data from HANA database tables, this SAP HANA database tutorial or Python tutorial can help you to start your code with the help of Python modules and library codes shown in following sections.
SAP HANA Database Connection using HDBCLI DBAPI in Python
On SAP Help Portal, connecting to SAP HANA databases using Python code is given with sample code blocks. ON referenced SAP HANA Client Interface Programming Reference page, basic SAP HANA connection methods are described for Python programmers.
After installing the Python driver for SAP HANA database connection, below Python code shared in this tutorial can be executed for validating SAP HANA database connections from Python environments.
If the above Python code executes successfully without any error, this verifies that the Python driver for connecting to SAP HANA database and the connection properties like host name (SAP HANA database server IP), port and user credentials (username and password).
(base) C:\WINDOWS\system32>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from hdbcli import dbapi
>>> dbapi.connect(address='10.10.101.55', port=30215, user='A00185555', password='Qwert1234*')
<hdbcli.dbapi.Connection object at 0x000001A61C32FF98>
>>>
In addition to the above code, I also want to provide a second code piece for Python developers. Here is sample Python code which can be used to connect SAP HANA database, query data from sample SAP HANA database table and close the connection to the database.
Above Pyhon code block demonstrates connection to SAP HANA database and returns sample data from system table dummy
Especially for the Cursor class methods and sample codes, Python programmers can reference to Cursor Class documentation which will lead them to build a full functional Python program which connect HANA database, queries data stored in the database, fetches and returns the data to process within Python code.
One importanat note, on the first referenced page, although the sample code is given with "host" attribute, the code should be used with "address" attribute. Otherwise, when the code is executed following error can occur taking attention to port attribute which is not the actual cause of the error.
hdbcli.dbapi.Error: (-10719, "Connect failed (invalid SERVERNODE ':30215')")
Install Python Driver for SAP HANA Database Connections
To install Python driver which will enable Python programmers to connect SAP HANA databases, following "pip" command can be executed