import psycopg2 # the postgreSQL package
import sys
import optparse
host_string = "localhost"
dbname_string = "mydatabase"
username_string = "myaccount"
from optparse import OptionParser
def main():
# The entry point : obtain the password and connect database.
parser=OptionParser()
parser.add_option("-p", "--password", dest="password", help="password for database account", metavar="PASSWORD")
parser.add_option("-o", "--output", dest="outfilename", help="output filename", metavar="OUTPUT_FILE")
(options, args) = parser.parse_args()
if len(sys.argv) < 2:
parser.print_help()
else:
print ("options:", str(options))
print ("arguments:", args)
print options.password
conn_string = "host="+"'"+host_string+"' "+"dbname="+"'"+ dbname_string+"' "+"user="+"'"+username_string+"' "+"password="+"'"+options.password+"'"
print "Connecting to database\n -> %s" % (conn_string)
try :
conn=psycopg2.connect(conn_string)
except:
print "unable to connect to database %s on host %s for user %s" %(dbname_string) %(host_string) %s(username_string)
print "Connected to database\n -> %s" % (conn_string)
cur=conn.cursor() # obtain the curser to execute SQL queries
cur.execute ("""SELECT * from system_now;""") #execute SQL query
rows = cur.fetchall() # fetch all rows
for row in rows: #print rows
print " ", row[1]
main()
No comments:
Post a Comment