Monday 2 September 2013

Access Teradata from Python - Generic code to run any Teradata SQL using python

BTEQ is supported on the following platforms:
  • NCR UNIX SVR4 MP-RAS
  • IBM z/OS (MVS and USS)
  • z/OS VM
  • Microsoft Windows 2000, XP, and Server 2003,2008
  • Sun Solaris SPARC
  • Sun Solaris Opteron
  • IBM AIX
  • HP-UX PA-RISC and IA64
  • SUSE and Red Hat Linux

Since, we cannot call the BTEQ utility directly from Python, we would use the Shell script and the subprocess library of Pthon.

The below example shows the approach to access Teradata from python:
 

1. Write a shell script to do the Bteq login
Contents of the script(TDLogon.sh) will be :

#! /usr/bin/sh

echo " Logging in"
echo $1
Script=$1
echo $Script
bteq < $Script
echo "Logging off"

2. We pass to this script the name of the SQL to be run:
Contents of the SQL script (logon.sql):

--- Contents of the SQL script

.logon edwprod1/datasc1,science123;

.quit

3. Contents of the Python script will be:

#! /usr/bin/python

import subprocess
SqlScript = "logon.sql"
# This can be modified to take different SQL files as parameters

name = "sh -v TDLogon.sh " + SqlScript
print "variable is", name
process = subprocess.Popen(args=[name], shell=True)
#process = subprocess.Popen(args=['sh -v TDLogon.sh logon.sql'] , shell=True)


process.wait()
print "Bteq login testing"

4. Run the python script as :
>> python Unixrun.py



This approach can be further refined to replace the SQL script name as a parameter.
Then start using this script to run all your SQL code from Python.
 

If you like our website, please donate as it will help us in our philanthropic endeavours!! Thanks.