Lecture de PostgreSQL avec Python

ExempleSélection (select.py)

1
#!/usr/bin/python3
2
3
# http://initd.org/psycopg/docs/usage.html
4
5
import psycopg2
6
7
HOST = "localhost"
8
USER = "me"
9
PASSWORD = "secret"
10
DATABASE = "mydb"
11
12
# Open connection
13
conn = psycopg2.connect("host=%s dbname=%s user=%s password=%s" % (HOST, DATABASE, USER, PASSWORD))
14
15
# Open a cursor to send SQL commands
16
cur = conn.cursor()
17
18
# Execute a SQL SELECT command
19
sql = "SELECT * FROM t"
20
cur.execute(sql)
21
22
# Fetch data line by line
23
raw = cur.fetchone()
24
while raw:
25
    print (raw[0])
26
    print (raw[1])
27
    raw = cur.fetchone()
28
29
# Close connection
30
conn.close()
31
1
$ ./select.py 
2
Hello
3
1

ComplémentDocumentation du module psycopg2