SAP DB용 Python Client입니다
기존의 dbmcli를 가지고 여러 쿼리를 사용해 보기에는 불편함이 있어서 mysql, psql 등 처럼 약간 편하게(?) 사용할 수 있도록 readline을 이용해서 만들었습니다.
일단 기본적인 쿼리의 작성은 가능하니 유용하게 쓰시기 바랍니다
#!/bin/env python
#
# SAP DB Python Client
# Made by MC Yi (netb@netb.co.kr)
#
import os
import sys
import string
import atexit
import readline
import getopt
import sapdb
def program_end():
print "Exit"
try:
conn.release()
except:
pass
try:
readline.write_history_file(histfile)
except IOError:
pass
def do_select(query):
try:
result = conn.sql(query)
except:
print "You have an error in your SQL syntax near '" + query + "'"
return
i = 0
strTitle = ''
strBar = ''
while i < result.columnCount():
strTitle = strTitle + result.columnInfo(i)[0] + '\t'
strBar = strBar + '-' * len(result.columnInfo(i)[0]) + '\t'
i = i + 1
print strTitle
print strBar
i = 0
for row in result:
for col in row:
print col,
print '\t',
print
i = i + 1
print str(i) + ' rows in set\n'
def do_execute(query):
try:
conn.sql(query)
except:
print "You have an error in your SQL syntax near '" + query + "'"
def usage():
print 'Usage: sapdb -u user -p password [OPTIONS] database'
if len(sys.argv) <= 1:
usage()
sys.exit(2)
try:
opts, args = getopt.getopt(sys.argv[1:], "hd:u:p:s:", ["help", "db=", "user=", "pass=", "server="])
except getopt.GetoptError:
usage()
sys.exit(2)
dbname = ''
dbuser = ''
dbpass = ''
dbhost = ''
for o, a in opts:
if o in ("-h", "--help"):
usage()
sys.exit()
if o in ("-d", "--db"):
dbname = string.upper(a)
if o in ("-u", "--user"):
dbuser = string.upper(a)
if o in ("-p", "--pass"):
dbpass = string.upper(a)
if o in ("-s", "--server"):
dbhost = a
if args:
dbname = args[0]
if not dbname or not dbuser or not dbpass:
usage()
sys.exit()
if not dbhost:
dbhost = 'localhost'
histfile = os.path.join(os.environ['HOME'], '.sapdb_history')
try:
conn = sapdb.connect(dbuser, dbpass, dbname, dbhost)
except sapdb.SQLError:
print 'Unable to connect to database server'
sys.exit()
atexit.register(program_end)
try:
readline.read_history_file(histfile)
except IOError:
pass
allline = ''
prompt = 'sapdb>'
while 1:
line = string.strip(raw_input(prompt))
allline = allline + line + ' '
tempcommand = string.upper(allline[:4])
if tempcommand == 'QUIT' or tempcommand == 'EXIT':
break
if string.find(line, ';') == -1:
prompt = ' ->'
else:
allline = string.strip(string.replace(allline, ';', ''))
command = string.upper(string.split(allline, ' ', 1)[0])
if command == 'SELECT':
do_select(allline)
else:
do_execute(allline)
allline = ''
prompt = 'sapdb>'
|