Python操作PostgreSql数据库的方法(基本的增删改查)


Posted in Python onDecember 29, 2020

Python操作PostgreSql数据库(基本的增删改查)

操作数据库最快的方式当然是直接用使用SQL语言直接对数据库进行操作,但是偶尔我们也会碰到在代码中操作数据库的情况,我们可能用ORM类的库对数控库进行操作,但是当需要操作大量的数据时,ORM的数据显的太慢了。在python中,遇到这样的情况,我推荐使用psycopg2操作postgresql数据库

psycopg2

官方文档传送门: http://initd.org/psycopg/docs/index.html

简单的增删改查

连接

连接pg并创建表

PG_SQL_LOCAL = {
 'database': 'postgres',
 'user': 'postgres',
 'password': "8dsa581",
 # 'host':'10.27.78.1',
 'host': 'localhost'
}

def connectPostgreSQL():
 conn = psycopg2.connect(**PG_SQL_LOCAL)
 print('connect successful!')
 cursor = conn.cursor()
 cursor.execute('''
 create table public.members(
 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(**PG_SQL_LOCAL)
 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')")
 row = conn.fetchone()
 print(row)
 conn.commit()
 conn.close()

 print('insert records into public.memmber successfully')

  • fetchall() 一次性获取所有数据
  • fetchmany() 一次值提取2000条数据(使用服务端的游标)
def selectOperate():
 conn = psycopg2.connect(**PG_SQL_LOCAL)
 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],)

 while True:
 rows = cursor.fetchmany(2000)
 if not rows:
  break
 for row in rows:
  # print('id=', row['id'], ',name=', row['name'], ',pwd=', row['pwd'], ',singal=', row['singal'],)
  rid,name,pwd,singal = row
  print(rid,name,pwd,singal)
  # print('id=', row[0], ',name=', row[1], ',pwd=', row[2], ',singal=', row[3], )
 conn.close()

更新数据

def updateOperate():
 conn = psycopg2.connect(**PG_SQL_LOCAL)
 cursor=conn.cursor()
 result = cursor.execute("update public.member set name='member X' where id=3")
 print(result)
 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(**PG_SQL_LOCAL)
 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()

补充,增加的字段带有时间格式

带有时间格式是,只需要传入时间格式的字符串(‘2017-05-27')即可,PG会自动识别

cur.execute("INSERT INTO Employee "
  "VALUES('Gopher', 'China Beijing', 100, '2017-05-27')")
# 查询数据
cur.execute("SELECT * FROM Employee")
rows = cur.fetchall()
for row in rows:
 print('name=' + str(row[0]) + ' address=' + str(row[1]) +
  ' age=' + str(row[2]) + ' date=' + str(row[3]), type(row[3]))

 # 插入数据
 sql = """INSERT INTO Employees VALUES(%s, %s, %s,%s) """
 var = []
 var.append([row[0], row[1], row[2], row[3]])
 cur.executemany(sql, var)

# 提交事务
conn.commit()

# 关闭连接
conn.close()

到此这篇关于Python操作PostgreSql数据库(基本的增删改查)的文章就介绍到这了,更多相关Python操作PostgreSql数据库内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python编写暴力破解FTP密码小工具
Nov 19 Python
python+pyqt实现12306图片验证效果
Oct 25 Python
python如何将图片转换为字符图片
Aug 19 Python
matplotlib.pyplot画图 图片的二进制流的获取方法
May 24 Python
Django1.9 加载通过ImageField上传的图片方法
May 25 Python
python读取一个目录下所有txt里面的内容方法
Jun 23 Python
python使用epoll实现服务端的方法
Oct 16 Python
Python实现的服务器示例小结【单进程、多进程、多线程、非阻塞式】
May 23 Python
scrapy数据存储在mysql数据库的两种方式(同步和异步)
Feb 18 Python
为什么说python适合写爬虫
Jun 11 Python
python中关于数据类型的学习笔记
Jul 19 Python
Python如何配置环境变量详解
May 18 Python
python中uuid模块实例浅析
Dec 29 #Python
python中pickle模块浅析
Dec 29 #Python
vue.js刷新当前页面的实例讲解
Dec 29 #Python
Python实现对word文档添加密码去除密码的示例代码
Dec 29 #Python
利于python脚本编写可视化nmap和masscan的方法
Dec 29 #Python
Python基于mediainfo批量重命名图片文件
Dec 29 #Python
用python批量下载apk
Dec 29 #Python
You might like
PHP session有效期问题
2009/04/26 PHP
使用php+Ajax实现唯一校验实现代码[简单应用]
2011/11/29 PHP
ThinkPHP3.1的Widget新用法
2014/06/19 PHP
十大使用PHP框架的理由
2015/09/26 PHP
php基于jquery的ajax技术传递json数据简单实例
2016/04/15 PHP
巧妙破除网页右键禁用的十大绝招
2006/08/12 Javascript
jquery 1.4.2发布!主要是性能与API
2010/02/25 Javascript
jquery下动态显示jqGrid以及jqGrid的属性设置容易出现问题的解决方法
2010/10/22 Javascript
Jquery插件 easyUI属性汇总
2011/01/19 Javascript
基于Jquery制作的幻灯片图集效果打包下载
2011/02/12 Javascript
jquery实现多行文字图片滚动效果示例代码
2014/10/10 Javascript
JQuery入门基础小实例(1)
2015/09/17 Javascript
解决js页面滚动效果scrollTop在FireFox与Chrome浏览器间的兼容问题的方法
2015/12/03 Javascript
详解Bootstrap插件
2016/04/25 Javascript
BootStrap网页中代码显示用法详解
2016/10/21 Javascript
JavaScript表单验证的两种实现方法
2017/02/11 Javascript
JavaScript 过滤关键字
2017/03/20 Javascript
vue-scroller记录滚动位置的示例代码
2018/01/17 Javascript
解决在vue项目中,发版之后,背景图片报错,路径不对的问题
2018/03/06 Javascript
初学node.js中实现删除用户路由
2019/05/27 Javascript
Vue 3.x+axios跨域方案的踩坑指南
2019/07/04 Javascript
Python爬虫之正则表达式的使用教程详解
2018/10/25 Python
Python OpenCV读取png图像转成jpg图像存储的方法
2018/10/28 Python
python烟花效果的代码实例
2020/02/25 Python
Python爬虫入门教程02之笔趣阁小说爬取
2021/01/24 Python
生产部主管岗位职责
2014/01/06 职场文书
市场营销调查计划书
2014/05/02 职场文书
文明礼仪演讲稿
2014/05/12 职场文书
2015年爱国卫生工作总结
2015/04/22 职场文书
社区禁毒宣传活动总结
2015/05/07 职场文书
军训阅兵新闻稿
2015/07/17 职场文书
高一军训感想
2015/08/07 职场文书
医院中层管理人员培训心得体会
2016/01/11 职场文书
聊一聊python常用的编程模块
2021/05/14 Python
解决Pytorch修改预训练模型时遇到key不匹配的情况
2021/06/05 Python
Python编程super应用场景及示例解析
2021/10/05 Python