本文測試環境爲Windows 7和PostgreSQL 10.3。數據庫
首先檢查安裝psycopg2。測試
pip install psycopg2
建立數據庫鏈接,執行數據庫語句。fetch
import psycopg2 #建立數據庫鏈接,數據庫配置信息根據實際狀況填寫 LocalPostgreSQLConnection = psycopg2.connect( host="127.0.0.1", port="5432",database="test", user="root", password="root") cur = LocalPostgreSQLConnection.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);''') #提交事務,未提交數據庫沒法查詢結果 LocalPostgreSQLConnection.commit() #關閉數據庫鏈接 LocalPostgreSQLConnection.close()
數據插入實例。code
import psycopg2 LocalPostgreSQLConnection=psycopg2.connect(host="127.0.0.1",port="5432",database="test",user="root",password="root") cur=LocalPostgreSQLConnection.cursor() cur.execute(''' insert into company values(1,'Bill',22,'New York',22.50); ''') LocalPostgreSQLConnection.commit() LocalPostgreSQLConnection.close()
簡單查詢。事務
import psycopg2 LocalPostgreSQLConnection=psycopg2.connect(host="127.0.0.1",port="5432",database="test",user="root",password="root") cur=LocalPostgreSQLConnection.cursor() cur.execute("select id, name, address, salary from company") rows = cur.fetchall() #cursor.fetchall() 這個例程獲取全部查詢結果(剩餘)行,返回一個列表。空行時則返回空列表。 for row in rows: print("ID = ", row[0]) print("NAME = ", row[1]) print("ADDRESS = ", row[2]) print("SALARY = ", row[3], "\n") print("select database successfully") LocalPostgreSQLConnection.commit() LocalPostgreSQLConnection.close()