❖ Psycopg2 |
Psycopg2 is a Python module that provides
import psycopg2
Note:
psycopg2
❖ Database connection |
conn = psycopg2.connect(
)
connection
psql
connection
dbname
user
password
host
port
dbname
❖ Example: connecting to a database |
Simple script that connects and then closes connection
import psycopg2 try: conn = psycopg2.connect("dbname=mydb") print(conn) # state of connection after opening conn.close() print(conn) # state of connection after closing except Exception as e: print("Unable to connect to the database")
which, if mydb
$ python3 ex1.py <connection object at 0xf67186ec; dsn: 'dbname=mydb', closed: 0> <connection object at 0xf67186ec; dsn: 'dbname=mydb', closed: 1>
❖ Example: connecting to a database (cont) |
Example: change the script to get databaase name from command line
import sys import psycopg2 if len(sys.argv) < 2: print("Usage: opendb DBname") exit(1) db = sys.argv[1] try: conn = psycopg2.connect("dbname="+db) print(conn) conn.close() print(conn) except Exception as e: print(f"Unable to connect to database {db}")
❖ Operations on connection |
cur = conn.cursor()
cursor
conn.close()
conn
conn.commit()
commit()
❖ Database Cursor |
Cursor
Cursor
connection
cursor
cur
cur = conn.cursor()
❖ Operations on cursor |
cur.execute(
,
)
# run a fixed query cur.execute("select * from R where x = 1"); # run a query with values inserted cur.execute("select * from R where x = %s", (1,)) cur.execute("select * from R where x = %s", [1]) # run a query stored in a variable query = "select * from Students where name ilike %s" pattern = "%mith%" cur.execute(query, [pattern])
❖ Operations on cursor |
cur.mogrify(
,
)
execute()
query = "select * from R where x = %s" print(cur.mogrify(query, [1])) Produces: b'select * from R where x = 1' query = "select * from R where x = %s and y = %s" print(cur.mogrify(query, [1,5])) Produces: b'select * from R where x = 1 and y = 5' query = "select * from Students where name ilike %s" pattern = "%mith%" print(cur.mogrify(query, [pattern])) Produces: b"select * from Students where name ilike '%mith%'" query = "select * from Students where family = %s" fname = "O'Reilly" print(cur.mogrify(query, [fname])) Produces: b"select * from Students where family = 'O''Reilly'"
❖ Operations on cursor |
list = cur.fetchall()
for
# table R contains (1,2), (2,1), ... cur.execute("select * from R") for tup in cur.fetchall(): x,y = tup print(x,y) # or print(tup[0],tup[1]) # prints 1 2 2 1 ...
❖ Operations on cursor |
tup = cur.fetchone()
while
# table R contains (1,2), (2,1), ... cur.execute("select * from R") while True: t = cur.fetchone() if t == None: break x,y = tup print(x,y) # prints 1 2 2 1 ...
❖ Operations on cursor |
tup = cur.fetchmany(
)
# table R contains (1,2), (2,1), ... cur.execute("select * from R") while True: tups = cur.fetchmany(3) if tups == []: break for tup in tups: x,y = tup print(x,y) # prints 1 2 2 1 ...
Produced: 26 Oct 2020