1. 程式人生 > 資料庫 >Python中用psycopg2模組操作PostgreSQL方法

Python中用psycopg2模組操作PostgreSQL方法

其實在Python中可以用來連線PostgreSQL的模組很多,這裡比較推薦psycopg2。psycopg2安裝起來非常的簡單(pip install psycopg2),這裡主要重點介紹下如何使用。

安裝psycopg2模組:

怎麼驗證是否已經安裝過psycopy2?

編寫上面程式碼,執行看是否丟擲缺少psycopg2模組。

安裝方法1:

1)使用psycopg2-2.4.2.win-amd64-py2.7-pg9.0.4-release.exe安裝,下載地址:http://vdisk.weibo.com/s/Cd8pPaw56Ozys

直接執行exe,不出錯誤,執行上邊程式碼驗證程式碼無錯誤,基本算是安裝完成了。

2)怎麼解除安裝?

2.1)找到安裝目錄:C:\Python27,發現下邊包含檔案:Removepsycopg2.exe,執行,來刪除;

2.2)如果執行失敗的話,進入目錄:C:\Python27\Lib\site-packages下,找到psycopg2資料夾和psycopg2-2.4.2-py2.7.egg-info檔案,右鍵刪除。

2.3)執行上邊的程式碼,確認是否刪除成功。

安裝方法2:

使用.whl安裝,下載地址:https://pypi.python.org/pypi/psycopg2/

下載檔案:psycopg2-2.6.2-cp27-none-win_amd64.whl

我這裡把psycopg2-2.6.2-cp27-none-win_amd64.whl拷貝到安裝目錄下Scripts資料夾中。

cmd中執行程式碼:pip install C:\Python27\Scripts\psycopg2-2.6.2-cp27-none-win_amd64.whl

執行上邊的程式碼,確認是否刪除成功。

通過psycopg2操作資料庫:

使用賬戶postgres,建立測試資料庫testdb。

參考yiibai.comAPI:

S.N. API & 描述

1 psycopg2.connect(database="testdb",user="postgres",password="cohondob",host="127.0.0.1",port="5432")

這個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()

這個例程獲取所有查詢結果(剩餘)行,返回一個列表。空行時則返回空列表。

開啟資料庫連線:

import os
import sys
import psycopg2
def connectPostgreSQL():
conn = psycopg2.connect(database="testdb",password="new.1234",port="5432")
print 'connect successful!'
if __name__=='__main__':
connectPostgreSQL()

建立表操作:

import os
import sys
import psycopg2
def connectPostgreSQL():
conn = psycopg2.connect(database="testdb",port="5432")
print 'connect successful!'
cursor=conn.cursor()
cursor.execute('''create table public.member(
id integer not null primary key,name varchar(32) not null,password varchar(32) not null,singal varchar(128)
)''')
conn.commit()
conn.close()
print 'table public.member is created!'
if __name__=='__main__':
connectPostgreSQL()

Insert 操作:

import os
 import sys
 import psycopg2
 
 def connectPostgreSQL():
   conn = psycopg2.connect(database="testdb",port="5432")
   print 'connect successful!'
   cursor=conn.cursor()
   cursor.execute('''create table public.member(
 id integer not null primary key,singal varchar(128)
 )''')
   conn.commit()
   conn.close()
   print 'table public.member is created!'
 def insertOperate():
   conn = psycopg2.connect(database="testdb",port="5432")
   cursor=conn.cursor()
   cursor.execute("insert into public.member(id,name,password,singal)\
 values(1,'member0','password0','signal0')")
   cursor.execute("insert into public.member(id,singal)\
 values(2,'member1','password1','signal1')")
   cursor.execute("insert into public.member(id,singal)\
 values(3,'member2','password2','signal2')")
   cursor.execute("insert into public.member(id,singal)\
 values(4,'member3','password3','signal3')")
   conn.commit()
   conn.close()
   
   print 'insert records into public.memmber successfully'
   
 if __name__=='__main__':
   #connectPostgreSQL()
insertOperate()

Select 操作:

import os
 import sys
 import psycopg2
 
 def connectPostgreSQL():
   conn = psycopg2.connect(database="testdb",singal varchar(128)
 )''')
   conn.commit()
   conn.close()
   print 'table public.member is created!'
 
 def insertOperate():
   conn = psycopg2.connect(database="testdb",'signal3')")
   conn.commit()
   conn.close()
   
   print 'insert records into public.memmber successfully'
 
 def selectOperate():
   conn = psycopg2.connect(database="testdb",port="5432")
   cursor=conn.cursor()
   cursor.execute("select id,singal from public.member where id>2")
   rows=cursor.fetchall()
   for row in rows:
     print 'id=',row[0],',name=',row[1],pwd=',row[2],singal=',row[3],'\n'
   conn.close()
   
 if __name__=='__main__':
   #connectPostgreSQL()
   #insertOperate()
   selectOperate()

結果:

Python 2.7.12 (v2.7.12:d33e0cf91556,Jun 27 2016,15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright","credits" or "license()" for more information.
>>> 
========== RESTART: C:\Users\Administrator\Desktop\mutilpleTest.py ==========
id= 3,name= member2,pwd= password2,singal= signal2 

id= 4,name= member3,pwd= password3,singal= signal3 

>>> 

update操作:

 import os
 import sys
 import psycopg2
 
 def connectPostgreSQL():
   conn = psycopg2.connect(database="testdb",'\n'
   conn.close()
 
 def updateOperate():
   conn = psycopg2.connect(database="testdb",port="5432")
   cursor=conn.cursor()
   cursor.execute("update public.member set name='update ...' where id=2")
   conn.commit()
   print "Total number of rows updated :",cursor.rowcount
 
   cursor.execute("select id,singal from public.member")
   rows=cursor.fetchall()
   for row in rows:
     print 'id=','\n'
   conn.close()
   
 if __name__=='__main__':
   #connectPostgreSQL()
   #insertOperate()
   #selectOperate()
   updateOperate()

結果:

Python 2.7.12 (v2.7.12:d33e0cf91556,"credits" or "license()" for more information.
>>> 
========== RESTART: C:\Users\Administrator\Desktop\mutilpleTest.py ==========
Total number of rows updated : 1
id= 1,name= member0,pwd= password0,singal= signal0 

id= 3,singal= signal3 

id= 2,name= update ...,pwd= password1,singal= signal1 

>>> 

Delete操作:

 import os
 import sys
 import psycopg2
 
 def connectPostgreSQL():
   conn = psycopg2.connect(database="testdb",'\n'
   conn.close()
 
 def deleteOperate():
   conn = psycopg2.connect(database="testdb",port="5432")  
   cursor=conn.cursor()
 
   cursor.execute("select id,'\n'
 
   print 'begin delete'
   cursor.execute("delete from public.member where id=2")
   conn.commit()  
   print 'end delete'
   print "Total number of rows deleted :",cursor.rowcount
   
   cursor.execute("select id,'\n'
   conn.close()
   
 if __name__=='__main__':
   #connectPostgreSQL()
   #insertOperate()
   #selectOperate()
   #updateOperate()
   deleteOperate()

結果:

Python 2.7.12 (v2.7.12:d33e0cf91556,"credits" or "license()" for more information.
>>> 
========== RESTART: C:\Users\Administrator\Desktop\mutilpleTest.py ==========
id= 1,singal= signal1 

begin delete
end delete
Total number of rows deleted : 1
id= 1,singal= signal3 

>>>