Python中用psycopg2模塊操作PostgreSQL方法
其實(shí)在Python中可以用來連接PostgreSQL的模塊很多,這里比較推薦psycopg2。psycopg2安裝起來非常的簡單(pip install psycopg2),這里主要重點(diǎn)介紹下如何使用。
安裝psycopg2模塊:
怎么驗(yàn)證是否已經(jīng)安裝過psycopy2?
編寫上面代碼,運(yùn)行看是否拋出缺少psycopg2模塊。
安裝方法1:
1)使用psycopg2-2.4.2.win-amd64-py2.7-pg9.0.4-release.exe安裝,下載地址:http://vdisk.weibo.com/s/Cd8pPaw56Ozys
直接運(yùn)行exe,不出錯誤,運(yùn)行上邊代碼驗(yàn)證代碼無錯誤,基本算是安裝完成了。
2)怎么卸載?
2.1)找到安裝目錄:C:\Python27,發(fā)現(xiàn)下邊包含文件:Removepsycopg2.exe,運(yùn)行,來刪除;
2.2)如果運(yùn)行失敗的話,進(jìn)入目錄:C:\Python27\Lib\site-packages下,找到psycopg2文件夾和psycopg2-2.4.2-py2.7.egg-info文件,右鍵刪除。
2.3)運(yùn)行上邊的代碼,確認(rèn)是否刪除成功。
安裝方法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中運(yùn)行代碼:pip install C:\Python27\Scripts\psycopg2-2.6.2-cp27-none-win_amd64.whl
運(yùn)行上邊的代碼,確認(rèn)是否刪除成功。
通過psycopg2操作數(shù)據(jù)庫:
使用賬戶postgres,創(chuàng)建測試數(shù)據(jù)庫testdb。
參考yiibai.comAPI:
S.N. API & 描述
1 psycopg2.connect(database="testdb", user="postgres", password="cohondob", host="127.0.0.1", port="5432")
這個API打開一個連接到PostgreSQL數(shù)據(jù)庫。如果成功打開數(shù)據(jù)庫時,它返回一個連接對象。
2 connection.cursor()
該程序創(chuàng)建一個光標(biāo)將用于整個數(shù)據(jù)庫使用Python編程。
3 cursor.execute(sql [, optional parameters])
此例程執(zhí)行SQL語句??杀粎?shù)化的SQL語句(即占位符,而不是SQL文字)。 psycopg2的模塊支持占位符用%s標(biāo)志
例如:cursor.execute("insert into people values (%s, %s)", (who, age))
4 curosr.executemany(sql, seq_of_parameters)
該程序執(zhí)行SQL命令對所有參數(shù)序列或序列中的sql映射。
5 curosr.callproc(procname[, parameters])
這個程序執(zhí)行的存儲數(shù)據(jù)庫程序給定的名稱。該程序預(yù)計(jì)為每一個參數(shù),參數(shù)的順序必須包含一個條目。
6 cursor.rowcount
這個只讀屬性,它返回?cái)?shù)據(jù)庫中的行的總數(shù)已修改,插入或刪除最后 execute*().
7 connection.commit()
此方法提交當(dāng)前事務(wù)。如果不調(diào)用這個方法,無論做了什么修改,自從上次調(diào)用commit()是不可見的,從其他的數(shù)據(jù)庫連接。
8 connection.rollback()
此方法會回滾任何更改數(shù)據(jù)庫自上次調(diào)用commit()方法。
9 connection.close()
此方法關(guān)閉數(shù)據(jù)庫連接。請注意,這并不自動調(diào)用commit()。如果你只是關(guān)閉數(shù)據(jù)庫連接而不調(diào)用commit()方法首先,那么所有更改將會丟失!
10 cursor.fetchone()
這種方法提取的查詢結(jié)果集的下一行,返回一個序列,或者無當(dāng)沒有更多的數(shù)據(jù)是可用的。
11 cursor.fetchmany([size=cursor.arraysize])
這個例程中取出下一個組的查詢結(jié)果的行數(shù),返回一個列表。當(dāng)沒有找到記錄,返回空列表。該方法試圖獲取盡可能多的行所顯示的大小參數(shù)。
12 cursor.fetchall()
這個例程獲取所有查詢結(jié)果(剩余)行,返回一個列表??招袝r則返回空列表。
打開數(shù)據(jù)庫連接:
import os import sys import psycopg2 def connectPostgreSQL(): conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432") print 'connect successful!' if __name__=='__main__': connectPostgreSQL()
創(chuàng)建表操作:
import os import sys import psycopg2 def connectPostgreSQL(): conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", 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", user="postgres", password="new.1234", host="127.0.0.1", 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!' def insertOperate(): conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", 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,name,password,singal)\ values(2,'member1','password1','signal1')") cursor.execute("insert into public.member(id,name,password,singal)\ values(3,'member2','password2','signal2')") cursor.execute("insert into public.member(id,name,password,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", user="postgres", password="new.1234", host="127.0.0.1", 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!' def insertOperate(): conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", 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,name,password,singal)\ values(2,'member1','password1','signal1')") cursor.execute("insert into public.member(id,name,password,singal)\ values(3,'member2','password2','signal2')") cursor.execute("insert into public.member(id,name,password,singal)\ values(4,'member3','password3','signal3')") conn.commit() conn.close() print 'insert records into public.memmber successfully' def selectOperate(): conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432") cursor=conn.cursor() cursor.execute("select id,name,password,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()
結(jié)果:
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", user="postgres", password="new.1234", host="127.0.0.1", 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!' def insertOperate(): conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", 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,name,password,singal)\ values(2,'member1','password1','signal1')") cursor.execute("insert into public.member(id,name,password,singal)\ values(3,'member2','password2','signal2')") cursor.execute("insert into public.member(id,name,password,singal)\ values(4,'member3','password3','signal3')") conn.commit() conn.close() print 'insert records into public.memmber successfully' def selectOperate(): conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432") cursor=conn.cursor() cursor.execute("select id,name,password,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() def updateOperate(): conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", 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,name,password,singal from public.member") 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() updateOperate()
結(jié)果:
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 ========== Total number of rows updated : 1 id= 1 ,name= member0 ,pwd= password0 ,singal= signal0 id= 3 ,name= member2 ,pwd= password2 ,singal= signal2 id= 4 ,name= member3 ,pwd= password3 ,singal= signal3 id= 2 ,name= update ... ,pwd= password1 ,singal= signal1 >>>
Delete操作:
import os import sys import psycopg2 def connectPostgreSQL(): conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", 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!' def insertOperate(): conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", 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,name,password,singal)\ values(2,'member1','password1','signal1')") cursor.execute("insert into public.member(id,name,password,singal)\ values(3,'member2','password2','signal2')") cursor.execute("insert into public.member(id,name,password,singal)\ values(4,'member3','password3','signal3')") conn.commit() conn.close() print 'insert records into public.memmber successfully' def selectOperate(): conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432") cursor=conn.cursor() cursor.execute("select id,name,password,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() def updateOperate(): conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", 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,name,password,singal from public.member") rows=cursor.fetchall() for row in rows: print 'id=',row[0], ',name=',row[1],',pwd=',row[2],',singal=',row[3],'\n' conn.close() def deleteOperate(): conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432") cursor=conn.cursor() cursor.execute("select id,name,password,singal from public.member") rows=cursor.fetchall() for row in rows: print 'id=',row[0], ',name=',row[1],',pwd=',row[2],',singal=',row[3],'\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,name,password,singal from public.member") 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() #updateOperate() deleteOperate()
結(jié)果:
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= 1 ,name= member0 ,pwd= password0 ,singal= signal0 id= 3 ,name= member2 ,pwd= password2 ,singal= signal2 id= 4 ,name= member3 ,pwd= password3 ,singal= signal3 id= 2 ,name= update ... ,pwd= password1 ,singal= signal1 begin delete end delete Total number of rows deleted : 1 id= 1 ,name= member0 ,pwd= password0 ,singal= signal0 id= 3 ,name= member2 ,pwd= password2 ,singal= signal2 id= 4 ,name= member3 ,pwd= password3 ,singal= signal3 >>>
相關(guān)文章
Python文件右鍵找不到IDLE打開項(xiàng)解決辦法
這篇文章主要介紹了Python文件右鍵找不到IDLE打開項(xiàng)解決辦法,本文使用注冊表解決了這個問題,需要的朋友可以參考下2015-06-06使用OpenCV獲取圖片連通域數(shù)量,并用不同顏色標(biāo)記函
這篇文章主要介紹了使用OpenCV獲取圖片連通域數(shù)量,并用不同顏色標(biāo)記函,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06詳解如何在cmd命令窗口中搭建簡單的python開發(fā)環(huán)境
這篇文章主要介紹了詳解如何在cmd命令窗口中搭建簡單的python開發(fā)環(huán)境,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08Python+OpenCV圖像處理之直方圖統(tǒng)計(jì)
直方圖就是對圖像的另外一種解釋,它描述了整幅圖像的灰度分布。通過直方圖我們可以對圖像的亮度、灰度分布、對比度等有了一個直觀的認(rèn)識。本文將為大家詳細(xì)介紹一下如何通過OpenCV實(shí)現(xiàn)直方圖統(tǒng)計(jì),感興趣的可以了解一下2021-12-12Django url,從一個頁面調(diào)到另個頁面的方法
今天小編就為大家分享一篇Django url,從一個頁面調(diào)到另個頁面的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08兩個元祖T1=(''a'', ''b''),T2=(''c'', ''d'')使用匿名函數(shù)將其轉(zhuǎn)變成[{''a'': '
今天小編就為大家分享一篇關(guān)于兩個元祖T1=('a', 'b'),T2=('c', 'd')使用匿名函數(shù)將其轉(zhuǎn)變成[{'a': 'c'},{'b': 'd'}]的幾種方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03