teadatasql_example

There are many ways to connect to a teradata database server using Python.  My favorite is the teradatasql driver for Python.  The following code provides a simple example of how to connect and perform a SQL query and print the result.  The variables td_hostname, td_username, td_password, td_logmech, and sql need to be changed for your teradata server and the SQL that you want to execute:

Information and software on this web site are provided under the Granite Mountain Informatics LLC End User License Agreement (EULA).

Send questions or comments to GraniteMountainInformaticsLLC@gmail.com.

"""
SYNOPSIS
python teradatasql_example.py
VERSION
202302121303
DESCRIPTION
An example of how to connect to a teradata database using the teradatasql driver for Python.
REFERENCE
https://pypi.org/project/teradatasql/
pip3 install teradatasql
"""
import datetimeimport globimport osimport teradatasqlimport reimport sysimport time
yyyymmddhhmmss = datetime.datetime.now().strftime("%Y%m%d%H%M%S")print(f"yyyymmddhhmmss='{yyyymmddhhmmss}'")
td_hostname = '192.168.64.2'td_username = 'dbc'td_password = 'dbc'td_logmech = 'TD2'
with teradatasql.connect(host = td_hostname, user = td_username, password = td_password, logmech = td_logmech) as td: print('Connected to Teradata: 192.168.64.2') cursor = td.cursor()
# excute SQL sql = 'SELECT * FROM DBC.DBCInfo;' try: cursor.execute(sql) lol = cursor.fetchall() print(f"lol='{lol}'") except: print(f"ERROR Try failed: {sys.exc_info()}")

The teradatasql_example.py can be executed using the following command line in linux:

python3 teradatasql_example.py