Skip to content

Instantly share code, notes, and snippets.

@rhossi

rhossi/testdb.py Secret

Created November 20, 2016 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhossi/98004f6e62795b67cb84997d8d4d2250 to your computer and use it in GitHub Desktop.
Save rhossi/98004f6e62795b67cb84997d8d4d2250 to your computer and use it in GitHub Desktop.
import psycopg2
import pprint
conn_string = "host='ec2-xx-xxx-xxx-xx.compute-1.amazonaws.com' dbname='dev' user='user' password='password'"
# print the connection string we will use to connect
print "Connecting to database\n ->%s" % (conn_string)
# get a connection, if a connect cannot be made an exception will be raised here
conn = psycopg2.connect(conn_string)
# conn.cursor will return a cursor object, you can use this cursor to perform queries
cursor = conn.cursor()
cursor.execute("drop table if exists testtable; create table testtable (testcol int)")
cursor.execute("INSERT INTO testtable (testcol) VALUES (1)")
# execute our Query
cursor.execute("SELECT * FROM testtable LIMIT 100")
# retrieve the records from the database
records = cursor.fetchall()
# print out the records using pretty print
# note that the NAMES of the columns are not shown, instead just indexes.
# for most people this isn't very useful so we'll show you how to return
# columns as a dictionary (hash) in the next example.
pprint.pprint(records)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment