使用Teradata模块将Python与Teradata连接起来

时间:2016-03-11 10:52:11

标签: python connection odbc teradata

我在Windows 7上安装了python 2.7.0和Teradata模块。我无法从python连接和quyey TD。

pip install Teradata

现在我想使用Python导入teradata模块并执行类似 -

的操作
  1. 向teradata发送查询并获取结果集。
  2. 检查是否与teradata建立了连接。 3.etc ..
  3. 请帮我编写代码,因为我是Python的新手,并且我没有任何信息可以连接到teradata。

3 个答案:

答案 0 :(得分:16)

有很多方法可以连接到Teradata并将表导出到Pandas。这是三个:

Using teradata module

# You can install teradata via PIP: pip install teradata
# to get a list of your odbc drivers names, you could do: teradata.tdodbc.drivers

import teradata
import pandas as pd

host,username,password = 'HOST','UID', 'PWD'
#Make a connection
udaExec = teradata.UdaExec (appName="test", version="1.0", logConsole=False)


with udaExec.connect(method="odbc",system=host, username=username,
                            password=password, driver="DRIVERNAME") as connect:

    query = "SELECT * FROM DATABASEX.TABLENAMEX;"

    #Reading query to df
    df = pd.read_sql(query,connect)
    # do something with df,e.g.
    print(df.head()) #to see the first 5 rows

Using pyodbc module

import pyodbc

 #You can install teradata via PIP: pip install pyodbc
 #to get a list of your odbc drivers names, you could do: pyodbc.drivers()

#Make a connection
link = 'DRIVER={DRIVERNAME};DBCNAME={hostname};UID={uid};PWD={pwd}'.format(
                      DRIVERNAME=DRIVERNAME,hostname=hostname,  
                      uid=username, pwd=password)
with pyodbc.connect(link,autocommit=True) as connect:

    #Reading query to df
    df = pd.read_sql(query,connect)

使用sqlalchemy Module

 #You can install sqlalchemy via PIP: pip install sqlalchemy-teradata
 #Note: It is not pip install sqlalchemy. If you already have sqlalchemy, you still need sqlalchemy-teradata to get teradata dialects

from sqlalchemy import create_engine

#Make a connection

link = 'teradata://{username}:{password}@{hostname}/?driver={DRIVERNAME}'.format(
               username=username,hostname=hostname,DRIVERNAME=DRIVERNAME)

with create_engine(link) as connect:

    #Reading query to df
    df = pd.read_sql(query,connect)

使用giraffez module还有第四种方法。我喜欢使用这个模块,因为它附带了MLOAD,FASTLOAD,BULKEXPORT等。初学者的唯一问题是它的要求(例如C / C ++编译器,Teradata CLIv2和TPT API头文件/ lib文件)。

注意:更新了13-07-2018,使用上下文管理器确保会话结束

更新:31-10-2018:使用teradata将数据从df发送到teradata

我们可以将数据从df发送到Teradata。避免' odbc' 1 MB限制以及odbc驱动程序依赖,我们可以使用' rest'方法。我们需要主机ip_address,而不是驱动程序参数。 NB: df中列的顺序应与Teradata表中的列顺序相匹配。

import teradata
import pandas as pd

# HOST_IP can be found by executing *>>nslookup viewpoint* or *ping  viewpoint* 
udaExec = teradata.UdaExec (appName="test", version="1.0", logConsole=False) 
with udaExec.connect(method="rest",system="DBName", username="UserName",
                      password="Password", host="HOST_IP_ADDRESS") as connect:

    data = [tuple(x) for x in df.to_records(index=False)]

    connect.executemany("INSERT INTO DATABASE.TABLEWITH5COL") 
                values(?,?,?,?,?)",data,batch=True)

使用' odbc',您必须将数据块化为少于1MB的块以避免" [HY001] [Teradata] [ODBC Teradata Driver]内存分配错误"错误:例如。

import teradata
import pandas as pd
import numpy as np

udaExec = teradata.UdaExec (appName="test", version="1.0", logConsole=False)

with udaExec.connect(method="odbc",system="DBName", username="UserName",
                      password="Password", driver="DriverName") as connect:

    #We can divide our huge_df to small chuncks. E.g. 100 churchs
    chunks_df = np.array_split(huge_df, 100)

    #Import chuncks to Teradata
    for i,_ in enumerate(chunks_df):

        data = [tuple(x) for x in chuncks_df[i].to_records(index=False)]
        connect.executemany("INSERT INTO DATABASE.TABLEWITH5COL values(?,?,?,?,?)",data,batch=True)

答案 1 :(得分:4)

从互联网下载Teradata Python模块和python pyodbc.pyd。 使用cmd install setup.py安装。

以下是连接teradata和提取数据的示例脚本:

import teradata
import pyodbc
import sys



udaExec = teradata.UdaExec (appName="HelloWorld", version="1.0",
        logConsole=False)

session = udaExec.connect(method="odbc", dsn="prod32",
        username="PRODRUN", password="PRODRUN");

i = 0
REJECTED = 'R';

f = file("output.txt","w");sys.stdout=f

cursor =  session.cursor();

ff_remaining = 0;

cnt = cursor.execute("SELECT  SEQ_NO,FRQFBKDC,PNR_RELOC FROM ttemp.ffremaining ORDER BY 1,2,3 ").rowcount;
rows = cursor.execute("SELECT  SEQ_NO,FRQFBKDC,PNR_RELOC FROM ttemp.ffremaining ORDER BY 1,2,3 ").fetchall();


for i in range(cnt):
    ff_remaining = cursor.execute("select count(*) as coun from  ttemp.ffretroq_paxoff where seq_no=? and status <> ?",(rows[i].seq_no,REJECTED)).fetchall();
    print ff_remaining[0].coun, rows[i].seq_no, REJECTED;

答案 2 :(得分:3)

要添加到Prayson's答案中,可以使用teradatasql程序包(found on pypi)。该软件包不需要您安装Teradata驱动程序(此软件包除外)。像这样使用它:

import teradatasql
import pandas as pd

with teradatasql.connect(host='host', user='username', password='password') as connect:
    data = pd.read_sql('select top 5 * from table_name;', connect)