Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- import psycopg2
- import sys
- import pprint
- class ConnectionTest():
- def __init__(self):
- #start of script
- #Define our connection string
- databaseName = 'kexp'
- databaseUser = 'kexp_user'
- databasePswd = 'kexp_pass'
- databaseHost = 'localhost'
- conn_string = "dbname='%s' user='%s' password='%s' host='%s'" % (databaseName, databaseUser, databasePswd, databaseHost)
- # print the connection string we will use to connect
- print "Connecting to database\n ->%s" % (conn_string)
- try:
- # get a connection, if a connect cannot be made an exception will be raised here
- self.conn = psycopg2.connect(conn_string)
- # conn.cursor will return a cursor object, you can use this cursor to perform queries
- print "Connected!\n"
- except:
- # Get the most recent exception
- exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
- # Exit the script and print an error telling what happened.
- sys.exit("Database connection failed!\n ->%s" % (exceptionValue))
- def runCommand(self):
- try:
- print "fuck"
- cursor = self.conn.cursor()
- cursor.execute(
- """INSERT INTO kexp_test (artist, songtitle)
- VALUES (%s, %s);""",
- ('beyonce', 'fuck you'))
- records = self.cursor.fetchall()
- print "results:"
- for row in records:
- print " ", row[0]
- except:
- # Get the most recent exception
- exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
- # Exit the script and print an error telling what happened.
- sys.exit("Database connection failed!\n ->%s" % (exceptionValue))
- if __name__ == "__init__":
- sys.exit(__init__)
- x = ConnectionTest()
- #while 3 > 1:
- # command = raw_input('\nPlease enter a query:')
- # command = "\"" + command + "\""
- x.runCommand() #"INSERT INTO kexp_test ( artist, songtitle ) VALUES ( 'beyonce', 'crazy in love' );"
- #SELECT * from kexp_test
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement