Teradata SQL Driver for Python

20.0.0.55 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to a Teradata database, execute DDL and DML statements, commit changes, and query data using the `teradatasql` driver. It highlights the importance of using `os.environ.get` for sensitive credentials and proper resource management by closing cursors and connections. Note that `autocommit` is `False` by default, requiring explicit `con.commit()`.

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.")

view raw JSON →