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(一)Python环境安装
Aug 20 Python
Python数据结构与算法之链表定义与用法实例详解【单链表、循环链表】
Sep 28 Python
python实现接口并发测试脚本
Jun 25 Python
Python分割训练集和测试集的方法示例
Sep 19 Python
python 利用pyttsx3文字转语音过程详解
Sep 25 Python
如何在django中添加日志功能
Feb 06 Python
python 画条形图(柱状图)实例
Apr 24 Python
浅谈tensorflow中dataset.shuffle和dataset.batch dataset.repeat注意点
Jun 08 Python
详解使用python爬取抖音app视频(appium可以操控手机)
Jan 26 Python
解决import tensorflow导致jupyter内核死亡的问题
Feb 06 Python
Python中的嵌套循环详情
Mar 23 Python
Python数组变形的几种实现方法
May 30 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
咖啡的传说和历史
2021/03/03 新手入门
IIS下PHP的三种配置方式对比
2014/11/20 PHP
php安装php_rar扩展实现rar文件读取和解压的方法
2016/11/17 PHP
PHP Post获取不到非表单数据的问题解决办法
2018/02/27 PHP
PHP简单实现正则匹配省市区的方法
2018/04/13 PHP
laravel-admin 中列表筛选方法
2019/10/03 PHP
Laravel5.1 框架响应基本用法实例分析
2020/01/04 PHP
PHP高并发和大流量解决方案整理
2019/12/24 PHP
php数组函数array_push()、array_pop()及array_shift()简单用法示例
2020/01/26 PHP
jQuery之折叠面板的深入解析
2013/06/19 Javascript
jquery 获取标签名(tagName)示例代码
2013/07/11 Javascript
js post提交调用方法
2014/02/12 Javascript
JavaScript数组常用方法
2015/03/02 Javascript
javascript生成随机数方法汇总
2015/11/12 Javascript
解决Window10系统下Node安装报错的问题分析
2016/12/13 Javascript
微信小程序 高德地图SDK详解及简单实例(源码下载)
2017/01/11 Javascript
JavaScript实现256色转灰度图
2017/02/22 Javascript
使用SVG基本操作API的实例讲解
2017/09/14 Javascript
浅谈vue的props,data,computed变化对组件更新的影响
2018/01/16 Javascript
vue2.0实现前端星星评分功能组件实例代码
2018/02/12 Javascript
JavaScript分步实现一个出生日期的正则表达式
2018/03/22 Javascript
Vue动态加载异步组件的方法
2018/11/21 Javascript
[08:06]DOTA2-DPC中国联赛 正赛 PSG.LGD vs Elephant 选手采访
2021/03/11 DOTA
连接Python程序与MySQL的教程
2015/04/29 Python
Python过滤列表用法实例分析
2016/04/29 Python
基于Python中求和函数sum的用法详解
2018/06/28 Python
python3中函数参数的四种简单用法
2018/07/09 Python
在vscode中配置python环境过程解析
2019/09/28 Python
巴基斯坦购物网站:Goto
2019/03/11 全球购物
PatPat德国:妈妈的每日优惠
2019/10/02 全球购物
介绍一下代理模式(Proxy)
2014/10/17 面试题
酒店七夕情人节活动策划方案
2014/08/24 职场文书
田径运动会通讯稿
2014/09/13 职场文书
小学班主任自我评价
2015/03/11 职场文书
电影地道战观后感
2015/06/04 职场文书
高中生物教学反思
2016/02/20 职场文书