2011/06/23

postgresDB operation with python

below code describes how to check if 'table' is exist in database or not using pg package. dirty code ... :-(


import pg
import sys

def is_table_exist1(dbobj, table):
""" return True if table is exist in database """
print "is_table_exist1 called"
try:
for i in dbobj.get_tables():
if i == table:
return True
except IndexError, (errno):
print "%s" %(errno)
return False
return False

def is_table_exist2(dbobj, table):
""" return True if table is exist in database """
print "is_table_exist2 called"
try:
print dbobj.get_attnames(table)
return True
except pg.ProgrammingError, (errno):
print "%s" %(errno)
return False

def main():
# set default hostname
pg.set_defhost('localhost')
defhost = pg.get_defhost()

# set default port number
pg.set_defport(5432)
defport = pg.get_defport()

# set default database
pg.set_defbase('testdb')
defbase = pg.get_defbase()

# initialize pg.DB object
mydb = pg.DB(user='postgres', passwd='postgres')

# print names of all databases
dblist = mydb.get_databases()

# check if table is exist in database
if is_table_exist1(mydb, 'public.foo') == False:
mydb.close()
sys.exit(1)

# check if table is exist in database
if is_table_exist2(mydb, 'public.foo') == False:
mydb.close()
sys.exit(1)

for r in mydb.query(
"SELECT v1, v2, v3, v4 FROM %s" % ('public.foo')
).dictresult():
print '%(v1)s %(v2)s %(v3)s %(v4)s' % r

#close dbobj
mydb.close()

if __name__ == "__main__":
main()

No comments:

Post a Comment

100