Python中用psycopg2模块操作PostgreSQL方法


Posted in Python onNovember 28, 2017

其实在Python中可以用来连接PostgreSQL的模块很多,这里比较推荐psycopg2。psycopg2安装起来非常的简单(pip install psycopg2),这里主要重点介绍下如何使用。

安装psycopg2模块:

怎么验证是否已经安装过psycopy2?

Python中用psycopg2模块操作PostgreSQL方法

编写上面代码,运行看是否抛出缺少psycopg2模块。

Python中用psycopg2模块操作PostgreSQL方法

安装方法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/

Python中用psycopg2模块操作PostgreSQL方法

下载文件: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

Python中用psycopg2模块操作PostgreSQL方法

运行上边的代码,确认是否删除成功。

通过psycopg2操作数据库:

使用账户postgres,创建测试数据库testdb。

Python中用psycopg2模块操作PostgreSQL方法

参考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", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
print 'connect successful!'
if __name__=='__main__':
connectPostgreSQL()

创建表操作:

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

结果:

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

结果:

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

结果:

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 

>>>

Python中用psycopg2模块操作PostgreSQL方法

Python 相关文章推荐
让python的Cookie.py模块支持冒号做key的方法
Dec 28 Python
Python全局变量操作详解
Apr 14 Python
Python实现简单的HttpServer服务器示例
Sep 25 Python
Python cookbook(数据结构与算法)根据字段将记录分组操作示例
Mar 19 Python
基于Python log 的正确打开方式
Apr 28 Python
Python 解决中文写入Excel时抛异常的问题
May 03 Python
利用python画出折线图
Jul 26 Python
Python中一些深不见底的“坑”
Jun 12 Python
python使用flask与js进行前后台交互的例子
Jul 19 Python
Tensorflow实现多GPU并行方式
Feb 03 Python
python应用Axes3D绘图(批量梯度下降算法)
Mar 25 Python
python中Pexpect的工作流程实例讲解
Mar 02 Python
Python搜索引擎实现原理和方法
Nov 27 #Python
python输入错误密码用户锁定实现方法
Nov 27 #Python
动态规划之矩阵连乘问题Python实现方法
Nov 27 #Python
Python基于贪心算法解决背包问题示例
Nov 27 #Python
Python标准模块--ContextManager上下文管理器的具体用法
Nov 27 #Python
利用信号如何监控Django模型对象字段值的变化详解
Nov 27 #Python
深入理解Python中range和xrange的区别
Nov 26 #Python
You might like
怎样在UNIX系统下安装MySQL
2006/10/09 PHP
初学CAKEPHP 基础教程
2009/11/02 PHP
PHP isset()与empty()的使用区别详解
2010/08/29 PHP
解析php中curl_multi的应用
2013/07/17 PHP
PHP的Socket通信之UDP通信实例
2015/07/02 PHP
PHP类的封装与继承详解
2015/09/29 PHP
如何通过View::first使用Laravel Blade的动态模板详解
2017/09/21 PHP
PHP设计模式(四)原型模式Prototype实例详解【创建型】
2020/05/02 PHP
jquery实现固定顶部导航效果(仿蘑菇街)
2013/03/21 Javascript
浅谈jquery中next与siblings的区别
2016/10/27 Javascript
javaScript基础详解
2017/01/19 Javascript
AngularJS实现路由实例
2017/02/12 Javascript
js链表操作(实例讲解)
2017/08/29 Javascript
详解a++和++a的区别
2017/08/30 Javascript
AngualrJs清除定时器遇到的坑
2017/10/13 Javascript
vue2.0路由切换后页面滚动位置不变BUG的解决方法
2018/03/14 Javascript
微信小程序实现人脸识别登陆的示例代码
2019/04/02 Javascript
探索JavaScript中私有成员的相关知识
2019/06/13 Javascript
[01:34]2014DOTA2展望TI 剑指西雅图VG战队专访
2014/06/30 DOTA
教你如何在Django 1.6中正确使用 Signal
2014/06/22 Python
Python定时执行之Timer用法示例
2015/05/27 Python
Python2.7基于笛卡尔积算法实现N个数组的排列组合运算示例
2017/11/23 Python
基于Python 装饰器装饰类中的方法实例
2018/04/21 Python
Python tkinter模版代码实例
2020/02/05 Python
Python3.6安装卸载、执行命令、执行py文件的方法详解
2020/02/20 Python
python3.6.8 + pycharm + PyQt5 环境搭建的图文教程
2020/06/11 Python
Python+Selenium随机生成手机验证码并检查页面上是否弹出重复手机号码提示框
2020/09/21 Python
Too Faced官网:美国知名彩妆品牌
2017/03/07 全球购物
Smilodox官方运动服装店:从运动服到健身配件
2020/08/27 全球购物
正风肃纪剖析材料
2014/02/18 职场文书
大学生迟到检讨书500字
2014/10/17 职场文书
《富饶的西沙群岛》教学反思
2016/02/16 职场文书
小学思想品德教学反思
2016/02/24 职场文书
公司年会晚会开幕词
2019/04/02 职场文书
python爬虫selenium模块详解
2021/03/30 Python
Django如何创作一个简单的最小程序
2021/05/12 Python