Python:使用psycopg2模块操作PostgreSQL

安装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()
  这个例程获取所有查询结果(剩余)行,返回一个列表。空行时则返回空列表。

  • 打开数据库连接:
 1 import os
 2 import sys
 3 import psycopg2
 4
 5 def connectPostgreSQL():
 6     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
 7     print ‘connect successful!‘
 8
 9 if __name__==‘__main__‘:
10     connectPostgreSQL()
11     
  • 创建表操作:
 1 import os
 2 import sys
 3 import psycopg2
 4
 5 def connectPostgreSQL():
 6     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
 7     print ‘connect successful!‘
 8     cursor=conn.cursor()
 9     cursor.execute(‘‘‘create table public.member(
10 id integer not null primary key,
11 name varchar(32) not null,
12 password varchar(32) not null,
13 singal varchar(128)
14 )‘‘‘)
15     conn.commit()
16     conn.close()
17     print ‘table public.member is created!‘
18
19 if __name__==‘__main__‘:
20     connectPostgreSQL()
21     
  • Insert 操作:
 1 import os
 2 import sys
 3 import psycopg2
 4
 5 def connectPostgreSQL():
 6     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
 7     print ‘connect successful!‘
 8     cursor=conn.cursor()
 9     cursor.execute(‘‘‘create table public.member(
10 id integer not null primary key,
11 name varchar(32) not null,
12 password varchar(32) not null,
13 singal varchar(128)
14 )‘‘‘)
15     conn.commit()
16     conn.close()
17     print ‘table public.member is created!‘
18
19 def insertOperate():
20     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
21     cursor=conn.cursor()
22     cursor.execute("insert into public.member(id,name,password,singal)23 values(1,‘member0‘,‘password0‘,‘signal0‘)")
24     cursor.execute("insert into public.member(id,name,password,singal)25 values(2,‘member1‘,‘password1‘,‘signal1‘)")
26     cursor.execute("insert into public.member(id,name,password,singal)27 values(3,‘member2‘,‘password2‘,‘signal2‘)")
28     cursor.execute("insert into public.member(id,name,password,singal)29 values(4,‘member3‘,‘password3‘,‘signal3‘)")
30     conn.commit()
31     conn.close()
32
33     print ‘insert records into public.memmber successfully‘
34
35 if __name__==‘__main__‘:
36     #connectPostgreSQL()
37     insertOperate()
38     
  • Select 操作:
 1 import os
 2 import sys
 3 import psycopg2
 4
 5 def connectPostgreSQL():
 6     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
 7     print ‘connect successful!‘
 8     cursor=conn.cursor()
 9     cursor.execute(‘‘‘create table public.member(
10 id integer not null primary key,
11 name varchar(32) not null,
12 password varchar(32) not null,
13 singal varchar(128)
14 )‘‘‘)
15     conn.commit()
16     conn.close()
17     print ‘table public.member is created!‘
18
19 def insertOperate():
20     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
21     cursor=conn.cursor()
22     cursor.execute("insert into public.member(id,name,password,singal)23 values(1,‘member0‘,‘password0‘,‘signal0‘)")
24     cursor.execute("insert into public.member(id,name,password,singal)25 values(2,‘member1‘,‘password1‘,‘signal1‘)")
26     cursor.execute("insert into public.member(id,name,password,singal)27 values(3,‘member2‘,‘password2‘,‘signal2‘)")
28     cursor.execute("insert into public.member(id,name,password,singal)29 values(4,‘member3‘,‘password3‘,‘signal3‘)")
30     conn.commit()
31     conn.close()
32
33     print ‘insert records into public.memmber successfully‘
34
35 def selectOperate():
36     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
37     cursor=conn.cursor()
38     cursor.execute("select id,name,password,singal from public.member where id>2")
39     rows=cursor.fetchall()
40     for row in rows:
41         print ‘id=‘,row[0], ‘,name=‘,row[1],‘,pwd=‘,row[2],‘,singal=‘,row[3],‘\n‘
42     conn.close()
43
44 if __name__==‘__main__‘:
45     #connectPostgreSQL()
46     #insertOperate()
47     selectOperate()
48     

结果:

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操作:
 1 import os
 2 import sys
 3 import psycopg2
 4
 5 def connectPostgreSQL():
 6     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
 7     print ‘connect successful!‘
 8     cursor=conn.cursor()
 9     cursor.execute(‘‘‘create table public.member(
10 id integer not null primary key,
11 name varchar(32) not null,
12 password varchar(32) not null,
13 singal varchar(128)
14 )‘‘‘)
15     conn.commit()
16     conn.close()
17     print ‘table public.member is created!‘
18
19 def insertOperate():
20     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
21     cursor=conn.cursor()
22     cursor.execute("insert into public.member(id,name,password,singal)23 values(1,‘member0‘,‘password0‘,‘signal0‘)")
24     cursor.execute("insert into public.member(id,name,password,singal)25 values(2,‘member1‘,‘password1‘,‘signal1‘)")
26     cursor.execute("insert into public.member(id,name,password,singal)27 values(3,‘member2‘,‘password2‘,‘signal2‘)")
28     cursor.execute("insert into public.member(id,name,password,singal)29 values(4,‘member3‘,‘password3‘,‘signal3‘)")
30     conn.commit()
31     conn.close()
32
33     print ‘insert records into public.memmber successfully‘
34
35 def selectOperate():
36     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
37     cursor=conn.cursor()
38     cursor.execute("select id,name,password,singal from public.member where id>2")
39     rows=cursor.fetchall()
40     for row in rows:
41         print ‘id=‘,row[0], ‘,name=‘,row[1],‘,pwd=‘,row[2],‘,singal=‘,row[3],‘\n‘
42     conn.close()
43
44 def updateOperate():
45     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
46     cursor=conn.cursor()
47     cursor.execute("update public.member set name=‘update ...‘ where id=2")
48     conn.commit()
49     print "Total number of rows updated :", cursor.rowcount
50
51     cursor.execute("select id,name,password,singal from public.member")
52     rows=cursor.fetchall()
53     for row in rows:
54         print ‘id=‘,row[0], ‘,name=‘,row[1],‘,pwd=‘,row[2],‘,singal=‘,row[3],‘\n‘
55     conn.close()
56
57 if __name__==‘__main__‘:
58     #connectPostgreSQL()
59     #insertOperate()
60     #selectOperate()
61     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操作:
 1 import os
 2 import sys
 3 import psycopg2
 4
 5 def connectPostgreSQL():
 6     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
 7     print ‘connect successful!‘
 8     cursor=conn.cursor()
 9     cursor.execute(‘‘‘create table public.member(
10 id integer not null primary key,
11 name varchar(32) not null,
12 password varchar(32) not null,
13 singal varchar(128)
14 )‘‘‘)
15     conn.commit()
16     conn.close()
17     print ‘table public.member is created!‘
18
19 def insertOperate():
20     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
21     cursor=conn.cursor()
22     cursor.execute("insert into public.member(id,name,password,singal)23 values(1,‘member0‘,‘password0‘,‘signal0‘)")
24     cursor.execute("insert into public.member(id,name,password,singal)25 values(2,‘member1‘,‘password1‘,‘signal1‘)")
26     cursor.execute("insert into public.member(id,name,password,singal)27 values(3,‘member2‘,‘password2‘,‘signal2‘)")
28     cursor.execute("insert into public.member(id,name,password,singal)29 values(4,‘member3‘,‘password3‘,‘signal3‘)")
30     conn.commit()
31     conn.close()
32
33     print ‘insert records into public.memmber successfully‘
34
35 def selectOperate():
36     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
37     cursor=conn.cursor()
38     cursor.execute("select id,name,password,singal from public.member where id>2")
39     rows=cursor.fetchall()
40     for row in rows:
41         print ‘id=‘,row[0], ‘,name=‘,row[1],‘,pwd=‘,row[2],‘,singal=‘,row[3],‘\n‘
42     conn.close()
43
44 def updateOperate():
45     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
46     cursor=conn.cursor()
47     cursor.execute("update public.member set name=‘update ...‘ where id=2")
48     conn.commit()
49     print "Total number of rows updated :", cursor.rowcount
50
51     cursor.execute("select id,name,password,singal from public.member")
52     rows=cursor.fetchall()
53     for row in rows:
54         print ‘id=‘,row[0], ‘,name=‘,row[1],‘,pwd=‘,row[2],‘,singal=‘,row[3],‘\n‘
55     conn.close()
56
57 def deleteOperate():
58     conn = psycopg2.connect(database="testdb", user="postgres", password="new.1234", host="127.0.0.1", port="5432")
59     cursor=conn.cursor()
60
61     cursor.execute("select id,name,password,singal from public.member")
62     rows=cursor.fetchall()
63     for row in rows:
64         print ‘id=‘,row[0], ‘,name=‘,row[1],‘,pwd=‘,row[2],‘,singal=‘,row[3],‘\n‘
65
66     print ‘begin delete‘
67     cursor.execute("delete from public.member where id=2")
68     conn.commit()
69     print ‘end delete‘
70     print "Total number of rows deleted :", cursor.rowcount
71
72     cursor.execute("select id,name,password,singal from public.member")
73     rows=cursor.fetchall()
74     for row in rows:
75         print ‘id=‘,row[0], ‘,name=‘,row[1],‘,pwd=‘,row[2],‘,singal=‘,row[3],‘\n‘
76     conn.close()
77
78 if __name__==‘__main__‘:
79     #connectPostgreSQL()
80     #insertOperate()
81     #selectOperate()
82     #updateOperate()
83     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 

>>> 

参考文章:

http://www.cnblogs.com/qiongmiaoer/archive/2013/09/30/3346984.html

http://www.yiibai.com/html/postgresql/2013/080998.html

时间: 2024-11-07 04:00:14

Python:使用psycopg2模块操作PostgreSQL的相关文章

临时数据库之python用sqlite3模块操作sqlite

SQLite是一个包含在C库中的轻量级数据库.它并不需要独立的维护进程,并且允许使用非标准变体(nonstandard variant)的SQL查询语句来访问数据库. 一些应用可是使用SQLite保存内部数据.它也可以在构建应用原型的时候使用,以便于以后转移到更大型的数据库. SQLite的主要优点: 1. 一致性的文件格式: 在SQLite的官方文档中是这样解释的,我们不要将SQLite与Oracle或PostgreSQL去比较,与我们自定义格式的数据文件相比,SQLite不仅提供了很好的 移

python用ibm_db模块操作db2

安装模块的教程已经在本博客的其它文章中介绍,这里不再详述. 连接db2 conn=ibm_db.connect("DATABASE=%s;HOSTNAME=%s;PORT=%s;PROTOCOL=TCPIP;UID=%s;PWD=%s"%(database,hostname,port,user,password),"","") 查询语句 result = ibm_db.exec_immediate(conn,"select name,a

Python使用xlwt模块 操作Excel文件

导出Excel文件     1. 使用xlwt模块 import xlwt import xlwt    # 导入xlwt # 新建一个excel文件 file = xlwt.Workbook() #注意这里的Workbook首字母是大写,无语吧 # 新建一个sheet   table = file.add_sheet('sheet name') # 写入数据table.write(行,列,value) table.write(0,0,'test') # 如果对一个单元格重复操作,会引发 ret

python使用elasticsearch模块操作elasticsearch

1.创建索引 命令如下 from elasticsearch import Elasticsearch es = Elasticsearch([{"host":"10.87.6.3","port":9200},]) s = "test" + "python" try: ret = es.indices.create(index=s) except Exception as e: print(e) else:

python中os模块操作目录与文件名小结

(1). 创建目录: SigleDir = 'sigle_layer' MultiDir = 'D:\\Web\\multi_layer' 创建单层目录: os.mkdir(SigleDir) 创建多层目录: os.makedirs(MultiDir) (2). 文件路径和文件名的折分与合并 拆分:  dirname, filename = os.path.split('D:\\python_code\\split_functon.py') print 'dirname=',dirname,';

python之openpyxl模块操作

import openpyxl #写 # book = openpyxl.Workbook() # sheet = book.active #默认的sheet # #sheet2 = book.get_sheet_by_name('sheet1') # # sheet.append( ['id','username','password','error_count']) # # sheet.append( [1,'wyj','123456',0]) # # sheet.append( [2,'w

python 操作PostgreSQL

pip install psycopg Python psycopg2 模块APIs 以下是psycopg2的重要的的模块例程可以满足Python程序与PostgreSQL数据库的工作. S.N. API & 描述 1 psycopg2.connect(database="testdb", user="postgres", password="cohondob", host="127.0.0.1", port=&quo

Python 操作 PostgreSQL 数据库

我使用的是 Python 3.7.0 PostgreSQL可以使用psycopg2模块与Python集成. sycopg2是用于Python编程语言的PostgreSQL数据库适配器. psycopg2是非常小,快速,稳定的. 您不需要单独安装此模块,因为默认情况下它会随着Python 2.5.x版本一起发布. pip3 install python-psycopg2pip3 install psycopg2-binary 连接到数据库 以下Python代码显示了如何连接到现有的数据库. 如果数

python之OS模块(对文件or目录操作)

OS模块 os,语义为操作系统,包含普遍的操作系统功能,与具体的平台无关.python编程时,处理文件和目录这些操作,就比如说:显示当前目录下所有文件/删除某个文件/获取文件大小-- os模块不受平台限制,也就是说:当我们要在linux中显示当前命令时就要用到pwd命令,而Windows中cmd命令行下就要用到这个,例如:这时候我们使用python中os模块的os.path.abspath(name)功能,甭管是linux或者Windows都可以获取当前的绝对路径. 常见函数列表 os.name