Psycopg2

COMP3311 20T3 ♢ Psycopg2 ♢ [0/12]
❖ Psycopg2

Psycopg2 is a Python module that provides

In order to use Psycopg2 in a Python program

import psycopg2

Note:

COMP3311 20T3 ♢ Psycopg2 ♢ [1/12]
❖ Psycopg2 (cont)

Where psycopg2 fits in the PL/DB architecture


[Diagram:Pics/pldb/pypsy-arch.png]

COMP3311 20T3 ♢ Psycopg2 ♢ [2/12]
❖ Database connections

conn = psycopg2.connect(DB_connection_string)

DB connection string components On Grieg, only dbname is required.
COMP3311 20T3 ♢ Psycopg2 ♢ [3/12]
❖ 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 is accessible, produces output:

$ python3 ex1.py
<connection object at 0xf67186ec; dsn: 'dbname=mydb', closed: 0>
<connection object at 0xf67186ec; dsn: 'dbname=mydb', closed: 1>

COMP3311 20T3 ♢ Psycopg2 ♢ [4/12]
❖ 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}")

COMP3311 20T3 ♢ Psycopg2 ♢ [5/12]
❖ Operations on connections

cur = conn.cursor()


conn.close()
conn.commit()
Plus many others ... see Psycopg2 documentation
COMP3311 20T3 ♢ Psycopg2 ♢ [6/12]
❖ Database Cursors

Cursors are "pipelines" to the database

Cursor objects allow you to ...

Cursors are created from a database connection To set up a cursor object called cur ...

cur = conn.cursor()

COMP3311 20T3 ♢ Psycopg2 ♢ [7/12]
❖ Operations on cursors

cur.execute(SQL_statement, Values)

Examples:

# 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])

COMP3311 20T3 ♢ Psycopg2 ♢ [8/12]
❖ Operations on cursors (cont)

cur.mogrify(SQL_statement, Values)

Examples:

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'"

COMP3311 20T3 ♢ Psycopg2 ♢ [9/12]
❖ Operations on cursors (cont)

list = cur.fetchall()

Example:

# 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
...

COMP3311 20T3 ♢ Psycopg2 ♢ [10/12]
❖ Operations on cursors (cont)

tup = cur.fetchone()

Example:

# 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
...

COMP3311 20T3 ♢ Psycopg2 ♢ [11/12]
❖ Operations on cursors (cont)

tup = cur.fetchmany(nTuples)

Example:

# 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
...

COMP3311 20T3 ♢ Psycopg2 ♢ [12/12]


Produced: 26 Oct 2020