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实现数据分析
Jan 11 Python
python opencv之SURF算法示例
Feb 24 Python
TensorFlow用expand_dim()来增加维度的方法
Jul 26 Python
Python正则表达式指南 推荐
Oct 09 Python
python 函数内部修改外部变量的方法
Dec 18 Python
python 检查是否为中文字符串的方法
Dec 28 Python
python关闭占用端口方式
Dec 17 Python
基于python实现计算且附带进度条代码实例
Mar 31 Python
python编写实现抽奖器
Sep 10 Python
Python gevent协程切换实现详解
Sep 14 Python
Python3中FuzzyWuzzy库实例用法
Nov 18 Python
python opencv角点检测连线功能的实现代码
Nov 24 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
Windows下PHP5和Apache的安装与配置
2006/09/05 PHP
php你的验证码安全码?
2007/01/02 PHP
PHP程序员面试 切忌急功近利(更需要注重以后的发展)
2010/09/01 PHP
destoon实现底部添加你是第几位访问者的方法
2014/07/15 PHP
php实现与erlang的二进制通讯实例解析
2014/07/23 PHP
PHP面试题之文件目录操作
2015/10/15 PHP
WordPress中调试缩略图的相关PHP函数使用解析
2016/01/07 PHP
thinkPHP5.0框架开发规范简介
2017/03/25 PHP
Thinkphp框架使用list_to_tree 实现无限级分类列出所有节点示例
2020/04/04 PHP
jquery获取checkbox的值并post提交
2015/01/14 Javascript
使用jquery获取url以及jquery获取url参数的实现方法
2016/05/25 Javascript
Bootstrap前端开发案例二
2016/06/17 Javascript
JavaScript中使用webuploader实现上传视频功能(demo)
2017/04/10 Javascript
vue axios 在页面切换时中断请求方法 ajax
2018/03/05 Javascript
WebPack配置vue多页面的技巧
2018/05/15 Javascript
js动态设置select下拉菜单的默认选中项实例
2018/08/21 Javascript
独立部署小程序基于nodejs的服务器过程详解
2019/06/24 NodeJs
layerui代码控制tab选项卡,添加,关闭的实例
2019/09/04 Javascript
vue 避免变量赋值后双向绑定的操作
2020/11/07 Javascript
[03:04]DOTA2英雄基础教程 影魔
2013/12/11 DOTA
Python实现找出数组中第2大数字的方法示例
2018/03/26 Python
对python过滤器和lambda函数的用法详解
2019/01/21 Python
大家都说好用的Python命令行库click的使用
2019/11/07 Python
python 日志 logging模块详细解析
2020/03/31 Python
Python实现自动签到脚本的示例代码
2020/08/19 Python
Nike瑞士官网:Nike CH
2021/01/18 全球购物
解释下面关于J2EE的名词
2013/11/15 面试题
小学生作文评语
2014/04/18 职场文书
师范大学生求职信
2014/06/13 职场文书
医德医风个人工作总结2014
2014/11/14 职场文书
离婚协议书怎么写的
2014/12/14 职场文书
小学数学国培研修日志
2015/11/13 职场文书
2016高考寄语或鼓励的话语
2015/12/04 职场文书
小学语文课《掌声》教学反思
2016/03/03 职场文书
《亲亲我的妈妈》观后感(3篇)
2019/09/26 职场文书
pytorch MSELoss计算平均的实现方法
2021/05/12 Python