PostgreSQL可以用Python psycopg2模塊集成。 sycopg2是Python編程語言的PostgreSQL數據庫的適配器。 其程序代碼少,速度快,穩定。不需要單獨安裝這個模塊,因為它默認情況下被運往隨著Python版本在2.5.x一起的。如果不把它安裝在機器上,然後可以使用yum命令安裝它,如下所示:
$yum install python-psycopg2
要使用psycopg2的模塊,首先必須創建一個Connection對象,它表示數據庫然後再可以選擇創建游標對象,這將幫助執行的所有SQL語句。
以下是psycopg2的重要的的模塊例程可以滿足Python程序與PostgreSQL數據庫的工作。如果尋找一個更復雜的應用程序,那麼可以看看Python psycopg2的模塊的官方文檔。
這個API打開一個連接到PostgreSQL數據庫。如果成功打開數據庫時,它返回一個連接對象。
2 connection.cursor()該程序創建一個光標將用於整個數據庫使用Python編程。
3 cursor.execute(sql [, optional parameters])此例程執行SQL語句。可被參數化的SQL語句(即占位符,而不是SQL文字)。 psycopg2的模塊支持占位符用%s標志
例如:cursor.execute("insert into people values (%s, %s)", (who, age))
4 curosr.executemany(sql, seq_of_parameters)該程序執行SQL命令對所有參數序列或序列中的sql映射。
5 curosr.callproc(procname[, parameters])這個程序執行的存儲數據庫程序給定的名稱。該程序預計為每一個參數,參數的順序必須包含一個條目。
6 cursor.rowcount這個只讀屬性,它返回數據庫中的行的總數已修改,插入或刪除最後 execute*().
7 connection.commit()此方法提交當前事務。如果不調用這個方法,無論做了什麼修改,自從上次調用commit()是不可見的,從其他的數據庫連接。
8 connection.rollback()此方法會回滾任何更改數據庫自上次調用commit()方法。
9 connection.close()此方法關閉數據庫連接。請注意,這並不自動調用commit()。如果你只是關閉數據庫連接而不調用commit()方法首先,那麼所有更改將會丟失!
10 cursor.fetchone()這種方法提取的查詢結果集的下一行,返回一個序列,或者無當沒有更多的數據是可用的。
11 cursor.fetchmany([size=cursor.arraysize])這個例程中取出下一個組的查詢結果的行數,返回一個列表。當沒有找到記錄,返回空列表。該方法試圖獲取盡可能多的行所顯示的大小參數。
12 cursor.fetchall()這個例程獲取所有查詢結果(剩余)行,返回一個列表。空行時則返回空列表。
Python代碼顯示了如何連接到一個現有的數據庫。如果數據庫不存在,那麼它就會被創建,最終將返回一個數據庫對象。
#!/usr/bin/python import psycopg2 conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432") print "Opened database successfully"
在這裡,也可以提供數據庫testdb的名稱,如果數據庫成功打開,那麼它會給下面的消息:
Open database successfully
以下Python程序將使用以前創建的數據庫中創建一個表:
#!/usr/bin/python import psycopg2 conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432") print "Opened database successfully" cur = conn.cursor() cur.execute('''CREATE TABLE COMPANY (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL);''') print "Table created successfully" conn.commit() conn.close()
上述程序執行時,它會創建表COMPANY 在數據庫test.db中,它會顯示以下消息:
Opened database successfully Table created successfully
Python程序顯示了我們如何創建表COMPANY 在上面的例子中創建表中的記錄:
#!/usr/bin/python import psycopg2 conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432") print "Opened database successfully" cur = conn.cursor() cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 )"); cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Allen', 25, 'Texas', 15000.00 )"); cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )"); cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )"); conn.commit() print "Records created successfully"; conn.close()
上述程序執行時,它會創建COMPANY表中的記錄,並顯示以下兩行:
Opened database successfully Records created successfully
Python程序,顯示如何獲取並顯示COMPANY 表在上面的例子中創建的記錄:
#!/usr/bin/python import psycopg2 conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432") print "Opened database successfully" cur = conn.cursor() cur.execute("SELECT id, name, address, salary from COMPANY") rows = cur.fetchall() for row in rows: print "ID = ", row[0] print "NAME = ", row[1] print "ADDRESS = ", row[2] print "SALARY = ", row[3], " " print "Operation done successfully"; conn.close()
當上述程序執行時,它會產生以下結果:
Opened database successfully ID = 1 NAME = Paul ADDRESS = California SALARY = 20000.0 ID = 2 NAME = Allen ADDRESS = Texas SALARY = 15000.0 ID = 3 NAME = Teddy ADDRESS = Norway SALARY = 20000.0 ID = 4 NAME = Mark ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully
Python代碼顯示如何,我們可以使用UPDATE語句來更新記錄,然後從COMPANY表獲取並顯示更新的記錄:
#!/usr/bin/python import psycopg2 conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432") print "Opened database successfully" cur = conn.cursor() cur.execute("UPDATE COMPANY set SALARY = 25000.00 where ID=1") conn.commit print "Total number of rows updated :", cur.rowcount cur.execute("SELECT id, name, address, salary from COMPANY") rows = cur.fetchall() for row in rows: print "ID = ", row[0] print "NAME = ", row[1] print "ADDRESS = ", row[2] print "SALARY = ", row[3], " " print "Operation done successfully"; conn.close()
當上述程序執行時,它會產生以下結果:
Opened database successfully Total number of rows updated : 1 ID = 1 NAME = Paul ADDRESS = California SALARY = 25000.0 ID = 2 NAME = Allen ADDRESS = Texas SALARY = 15000.0 ID = 3 NAME = Teddy ADDRESS = Norway SALARY = 20000.0 ID = 4 NAME = Mark ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully
Python代碼顯示了如何我們可以使用DELETE語句刪除記錄,然後獲取並顯示COMPANY 表剩余的記錄:
#!/usr/bin/python import psycopg2 conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432") print "Opened database successfully" cur = conn.cursor() cur.execute("DELETE from COMPANY where ID=2;") conn.commit print "Total number of rows deleted :", cur.rowcount cur.execute("SELECT id, name, address, salary from COMPANY") rows = cur.fetchall() for row in rows: print "ID = ", row[0] print "NAME = ", row[1] print "ADDRESS = ", row[2] print "SALARY = ", row[3], " " print "Operation done successfully"; conn.close()
當上述程序執行時,它會產生以下結果:
Opened database successfully Total number of rows deleted : 1 ID = 1 NAME = Paul ADDRESS = California SALARY = 20000.0 ID = 3 NAME = Teddy ADDRESS = Norway SALARY = 20000.0 ID = 4 NAME = Mark ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully