Teradata SQL Driver for Python
teradatasql is the official Python driver for connecting to Teradata Vantage and other Teradata systems. It provides a DBAPI 2.0 compliant interface, allowing Python applications to connect to Teradata databases, execute SQL queries, and fetch results. The current stable version is 20.0.0.55. Teradata usually releases updates on an as-needed basis to support new features or address issues.
Warnings
- breaking Starting with version 20.0.0.0, the driver now maps SQL `DECIMAL` types to Python's `Decimal` objects by default, instead of `float`. This change improves precision but may require updates to existing code that expects `float` values for decimal columns.
- breaking Version 20.x introduced support for Teradata Vantage connection string formats and changed some default configuration settings. While traditional keyword arguments for `teradatasql.connect` are largely supported, existing code relying on specific parameter names or default behaviors (e.g., related to `logmech` or session settings) might need review.
- gotcha `teradatasql` defaults to `autocommit=False` (DBAPI 2.0 standard). This means `INSERT`, `UPDATE`, `DELETE`, and `DDL` statements will not be persisted to the database until `con.commit()` is explicitly called. Forgetting to commit will result in data not being saved.
- gotcha It is crucial to close both the cursor (`cur.close()`) and the connection (`con.close()`) objects when you are finished with them. Failing to do so can lead to resource leaks on both the client and server sides, exhausting connection pools or consuming memory.
Install
-
pip install teradatasql
Imports
- connect
import teradatasql con = teradatasql.connect(...)
Quickstart
import teradatasql
import os
# --- Configuration (replace with your Teradata connection details) ---
# It's recommended to use environment variables or a configuration management tool
HOST = os.environ.get('TERADATA_HOST', 'your_teradata_host')
USER = os.environ.get('TERADATA_USER', 'your_username')
PASSWORD = os.environ.get('TERADATA_PASSWORD', 'your_password')
DATABASE = os.environ.get('TERADATA_DATABASE', 'your_database_name') # Optional
if HOST == 'your_teradata_host':
print("Warning: Please configure TERADATA_HOST, TERADATA_USER, and TERADATA_PASSWORD environment variables or replace placeholders.")
exit()
con = None
cur = None
try:
# Connect to Teradata. For Teradata Vantage, the 'host' parameter is 'DBCName'.
# Additional parameters can be passed as keyword arguments or via a connection string.
# For instance, if you need a specific logon mechanism: logmech='TD2'
con = teradatasql.connect(host=HOST, user=USER, password=PASSWORD, database=DATABASE)
print("Successfully connected to Teradata.")
cur = con.cursor()
# Example: Create a table (if it doesn't exist)
try:
cur.execute("CREATE TABLE my_test_table (id INTEGER, name VARCHAR(100));")
print("Table 'my_test_table' created.")
except teradatasql.OperationalError as e:
if "already exists" in str(e).lower():
print("Table 'my_test_table' already exists.")
else:
raise # Re-raise other errors
# Example: Insert data
cur.execute("INSERT INTO my_test_table (id, name) VALUES (?, ?);", (1, 'Alice'))
cur.execute("INSERT INTO my_test_table (id, name) VALUES (?, ?);", (2, 'Bob'))
con.commit() # Commit the transaction as autocommit=False by default
print("Data inserted and committed.")
# Example: Query data
cur.execute("SELECT id, name FROM my_test_table ORDER BY id;")
print("\nFetched data:")
for row in cur.fetchall():
print(row)
# Example: Clean up (optional)
# cur.execute("DROP TABLE my_test_table;")
# con.commit()
# print("Table 'my_test_table' dropped.")
except teradatasql.Error as e:
print(f"Teradata SQL Error: {e}")
if con:
con.rollback() # Rollback in case of error
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
if cur:
cur.close()
print("Cursor closed.")
if con:
con.close()
print("Connection closed.")