在 Python 中连接到 Teradata 有不同的方法。以下列表并不详尽。
SQL炼金术
如果你想使用SQLAlchemy,你还需要安装包SQLAlchemy-Teradata。以下是连接方式:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base, DeferredReflection
from sqlalchemy.orm import scoped_session, sessionmaker
[...]
# Connect
engine = create_engine('teradata://' + user + ':' + password + '@' + host + ':22/' + database)
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
db_session.execute('SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;') # To avoid locking tables when doing select on tables
db_session.commit()
Base = declarative_base(cls=DeferredReflection)
Base.query = db_session.query_property()
然后你可以db_session
用来进行查询。请参阅SQLAlchemy 会话 API
数据库
如果您想使用Pyodbc,您首先需要在您的机器上安装 Teradata 驱动程序。我的示例,安装 Teradata 驱动程序后,我有以下条目/etc/odbcinst.ini
[Teradata]
Driver=/opt/teradata/client/16.00/odbc_64/lib/tdata.so
APILevel=CORE
ConnectFunctions=YYY
DriverODBCVer=3.51
SQLLevel=1
然后我可以连接以下内容:
import pyodbc
[...]
#Teradata Connection
connection= pyodbc.connect("driver={Teradata};dbcname=" + host + ";uid=" + user + ";pwd=" + pwd + ";charset=utf8;", autocommit=True)
connection.setdecoding(pyodbc.SQL_CHAR, encoding='utf-8')
connection.setdecoding(pyodbc.SQL_WCHAR, encoding='utf-8')
connection.setdecoding(pyodbc.SQL_WMETADATA, encoding='utf-8')
connection.setencoding(encoding='utf-8')
cursor= n.cursor()
cursor.execute("Select 'Hello World'")
for row in cursor:
print (row)