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异常学习笔记
Feb 03 Python
Python中使用socket发送HTTP请求数据接收不完整问题解决方法
Feb 04 Python
基于Python实现的百度贴吧网络爬虫实例
Apr 17 Python
python如何实现excel数据添加到mongodb
Jul 30 Python
浅析Python中signal包的使用
Nov 13 Python
python算法表示概念扫盲教程
Apr 13 Python
Python Pandas找到缺失值的位置方法
Apr 12 Python
python代码过长的换行方法
Jul 19 Python
在python中pandas的series合并方法
Nov 12 Python
Pytorch之保存读取模型实例
Dec 30 Python
pytorch如何冻结某层参数的实现
Jan 10 Python
Django 后台带有字典的列表数据与页面js交互实例
Apr 03 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计算程序运行时间的简单例子分享
2014/05/10 PHP
ThinkPHP函数详解之M方法和R方法
2015/09/10 PHP
两种php实现图片上传的方法
2016/01/22 PHP
PHP 开发者该知道的 5 个 Composer 小技巧
2016/02/03 PHP
PHP使用Nginx实现反向代理
2017/09/20 PHP
js form 验证函数 当前比较流行的错误提示
2009/06/23 Javascript
JS+CSS实现电子商务网站导航模板效果代码
2015/09/10 Javascript
纯js代码实现简单计算器
2015/12/02 Javascript
用JS中split方法实现彩色文字背景效果实例
2016/08/24 Javascript
javascript中的后退和刷新实现方法
2016/11/10 Javascript
js仿微信语音播放实现思路
2016/12/12 Javascript
详解基于原生JS验证表单组件xy-form
2019/08/20 Javascript
jQuery实现移动端笔触canvas电子签名
2020/05/21 jQuery
使用python编写android截屏脚本双击运行即可
2014/07/21 Python
Python常用库推荐
2016/12/04 Python
Python实现简易Web爬虫详解
2018/01/03 Python
对python中Librosa的mfcc步骤详解
2019/01/09 Python
Python字符串逆序输出的实例讲解
2019/02/16 Python
Python实现html转换为pdf报告(生成pdf报告)功能示例
2019/05/04 Python
Python3.5 win10环境下导入kera/tensorflow报错的解决方法
2019/12/19 Python
Python版中国省市经纬度
2020/02/11 Python
python实现一次性封装多条sql语句(begin end)
2020/06/06 Python
python生成word合同的实例方法
2021/01/12 Python
Canvas在超级玛丽游戏中的应用详解
2021/02/06 HTML / CSS
英国香水店:The Perfume Shop
2017/03/27 全球购物
澳大利亚家具和家居用品购物网站:Zanui
2018/12/29 全球购物
最新的大学生找工作自我评价
2013/09/29 职场文书
优秀信贷员先进事迹
2014/01/31 职场文书
保卫科工作岗位职责
2014/03/01 职场文书
家教广告词
2014/03/19 职场文书
省文明单位申报材料
2014/05/08 职场文书
服装设计师求职信
2014/06/04 职场文书
商场周年庆活动方案
2014/08/19 职场文书
单位员工收入证明样本
2014/10/09 职场文书
乡镇党的群众路线教育实践活动制度建设计划
2014/11/03 职场文书
医院保洁员岗位职责
2015/02/13 职场文书