一日一技:Python | PostgreSQL中的数据库管理
wptr33 2025-01-06 15:48 30 浏览
有几个python模块可以让我们使用PostgreSQL连接和操作数据库:
- Psycopg2
- pg8000
- py-postgresql
- PyGreSQL
Psycopg2是PostgreSQL最受欢迎的python驱动程序之一。 它被积极维护并为不同版本的python提供支持。 它还提供对线程的支持,并且可以在多线程应用程序中使用。 由于这些原因,它是开发人员的流行选择。
在这一小节中,我们将通过在python中构建一个简单的数据库管理系统来探索使用psycopg2使用PostgreSQl的功能。
安装模块:
sudo pip3 install psycopg2 #使用的是 Ubuntu系统注意:如果您使用的是Python2,请使用pip install代替pip3,不过python2.7版本已经不再维护,不推荐使用。
在您的系统中安装了psycopg之后,我们可以连接到数据库并在Python中执行查询。
创建数据库
在我们可以使用python访问数据库之前,我们需要在postgresql中创建数据库。 要创建数据库,请遵循以下步骤:
1.登录PostgreSQL.
sudo -u postgres psql2.配置密码.
\password然后将提示您输入密码。 记住这一点,因为我们将使用它来连接到Python中的数据库。
3.创建一个名为“ test”的数据库。 我们将连接到该数据库.
CREATE DATABASE test; #分号;别忘记带上配置数据库和密码后,退出psql服务器。
连接到数据库
connect()方法用于建立与数据库的连接。 它包含5个参数:
1.database:您要连接的数据库的名称
2.user:您本地系统的用户名
3.password:登录psql的密码
4.host:主机,默认情况下设置为localhost
5.port:端口号,默认为5432
conn = psycopg2.connect(
database="test",
user = "adith",
password = "password",
host = "localhost",
port = "5432")建立连接后,我们可以使用python操作数据库。
Cursor对象用于执行sql查询。 我们可以使用连接对象(conn)创建一个游标对象
cur = conn.cursor() 使用此对象,我们可以更改连接到的数据库。
执行完所有查询后,我们需要断开连接。 不断开连接不会导致任何错误,但是通常认为断开连接是一种好习惯。
conn.close() 执行查询
execute()方法采用一个参数,即要执行的SQL查询。 SQL查询采用包含SQL语句的字符串形式。
cur.execute("SELECT * FROM emp") 获得数据
一旦执行了查询,就可以使用fetchall()方法获取查询的结果。 此方法不带参数,并返回选择查询的结果。
res = cur.fetchall() 查询结果存储在res变量中.
全部放在一起
在PostgreSQL中创建数据库后,就可以使用python访问该数据库。 我们首先使用以下模式在数据库中创建一个名为test的emp表:(id INTEGER PRIMARY KEY,名称VARCHAR(10),salary INT,dept INT)。 创建表后,没有任何错误,我们将值插入表中。
插入值后,我们可以查询表以选择所有行,并使用fetchall()函数将其显示给用户。
# importing libraries
import psycopg2
# a function to connect to
# the database.
def connect():
# connecting to the database called test
# using the connect function
try:
conn = psycopg2.connect(database ="test",
user = "adith",
password = "password",
host = "localhost",
port = "5432")
# creating the cursor object
cur = conn.cursor()
except (Exception, psycopg2.DatabaseError) as error:
print ("Error while creating PostgreSQL table", error)
# returing the conn and cur
# objects to be used later
return conn, cur
# a function to create the
# emp table.
def create_table():
# connect to the database.
conn, cur = connect()
try:
# the test database contains a table called emp
# the schema : (id INTEGER PRIMARY KEY,
# name VARCHAR(10), salary INT, dept INT)
# create the emp table
cur.execute('CREATE TABLE emp (id INT PRIMARY KEY, name VARCHAR(10),
salary INT, dept INT)')
# the commit function permanently
# saves the changes made to the database
# the rollback() function can be used if
# there are any undesirable changes and
# it simply undoes the changes of the
# previous query
except:
print('error')
conn.commit()
# a function to insert data
# into the emp table
def insert_data(id = 1, name = '', salary = 1000, dept = 1):
conn, cur = connect()
try:
# inserting values into the emp table
cur.execute('INSERT INTO emp VALUES(%s, %s, %s, %s)',
(id, name, salary, dept))
except Exception as e:
print('error', e)
# commiting the transaction.
conn.commit()
# a function to fetch the data
# from the table
def fetch_data():
conn, cur = connect()
# select all the rows from emp
try:
cur.execute('SELECT * FROM emp')
except:
print('error !')
# store the result in data
data = cur.fetchall()
# return the result
return data
# a function to print the data
def print_data(data):
print('Query result: ')
print()
# iterating over all the
# rows in the table
for row in data:
# printing the columns
print('id: ', row[0])
print('name: ', row[1])
print('salary: ', row[2])
print('dept: ', row[3])
print('----------------------------------')
# function to delete the table
def delete_table():
conn, cur = connect()
# delete the table
try:
cur.execute('DROP TABLE emp')
except Exception as e:
print('error', e)
conn.commit()
# driver function
if __name__ == '__main__':
# create the table
create_table()
# inserting some values
insert_data(1, 'adith', 1000, 2)
insert_data(2, 'tyrion', 100000, 2)
insert_data(3, 'jon', 100, 3)
insert_data(4, 'daenerys', 10000, 4)
# getting all the rows
data = fetch_data()
# printing the rows
print_data(data)
# deleting the table
# once we are done with
# the program
delete_table() 输出:
- 上一篇:Delphi 数据库操作的简单封装
- 下一篇:python优雅执行SQL模板语句
相关推荐
- oracle数据导入导出_oracle数据导入导出工具
-
关于oracle的数据导入导出,这个功能的使用场景,一般是换服务环境,把原先的oracle数据导入到另外一台oracle数据库,或者导出备份使用。只不过oracle的导入导出命令不好记忆,稍稍有点复杂...
- 继续学习Python中的while true/break语句
-
上次讲到if语句的用法,大家在微信公众号问了小编很多问题,那么小编在这几种解决一下,1.else和elif是子模块,不能单独使用2.一个if语句中可以包括很多个elif语句,但结尾只能有一个...
- python continue和break的区别_python中break语句和continue语句的区别
-
python中循环语句经常会使用continue和break,那么这2者的区别是?continue是跳出本次循环,进行下一次循环;break是跳出整个循环;例如:...
- 简单学Python——关键字6——break和continue
-
Python退出循环,有break语句和continue语句两种实现方式。break语句和continue语句的区别:break语句作用是终止循环。continue语句作用是跳出本轮循环,继续下一次循...
- 2-1,0基础学Python之 break退出循环、 continue继续循环 多重循
-
用for循环或者while循环时,如果要在循环体内直接退出循环,可以使用break语句。比如计算1至100的整数和,我们用while来实现:sum=0x=1whileTrue...
- Python 中 break 和 continue 傻傻分不清
-
大家好啊,我是大田。...
- python中的流程控制语句:continue、break 和 return使用方法
-
Python中,continue、break和return是控制流程的关键语句,用于在循环或函数中提前退出或跳过某些操作。它们的用途和区别如下:1.continue(跳过当前循环的剩余部分,进...
- L017:continue和break - 教程文案
-
continue和break在Python中,continue和break是用于控制循环(如for和while)执行流程的关键字,它们的作用如下:1.continue:跳过当前迭代,...
- 作为前端开发者,你都经历过怎样的面试?
-
已经裸辞1个月了,最近开始投简历找工作,遇到各种各样的面试,今天分享一下。其实在职的时候也做过面试官,面试官时,感觉自己问的问题很难区分候选人的能力,最好的办法就是看看候选人的github上的代码仓库...
- 面试被问 const 是否不可变?这样回答才显功底
-
作为前端开发者,我在学习ES6特性时,总被const的"善变"搞得一头雾水——为什么用const声明的数组还能push元素?为什么基本类型赋值就会报错?直到翻遍MDN文档、对着内存图反...
- 2023金九银十必看前端面试题!2w字精品!
-
导文2023金九银十必看前端面试题!金九银十黄金期来了想要跳槽的小伙伴快来看啊CSS1.请解释CSS的盒模型是什么,并描述其组成部分。...
- 前端面试总结_前端面试题整理
-
记得当时大二的时候,看到实验室的学长学姐忙于各种春招,有些收获了大厂offer,有些还在苦苦面试,其实那时候的心里还蛮忐忑的,不知道自己大三的时候会是什么样的一个水平,所以从19年的寒假放完,大二下学...
- 由浅入深,66条JavaScript面试知识点(七)
-
作者:JakeZhang转发链接:https://juejin.im/post/5ef8377f6fb9a07e693a6061目录...
- 2024前端面试真题之—VUE篇_前端面试题vue2020及答案
-
添加图片注释,不超过140字(可选)...
- 今年最常见的前端面试题,你会做几道?
-
在面试或招聘前端开发人员时,期望、现实和需求之间总是存在着巨大差距。面试其实是一个交流想法的地方,挑战人们的思考方式,并客观地分析给定的问题。可以通过面试了解人们如何做出决策,了解一个人对技术和解决问...
- 一周热门
- 最近发表
-
- oracle数据导入导出_oracle数据导入导出工具
- 继续学习Python中的while true/break语句
- python continue和break的区别_python中break语句和continue语句的区别
- 简单学Python——关键字6——break和continue
- 2-1,0基础学Python之 break退出循环、 continue继续循环 多重循
- Python 中 break 和 continue 傻傻分不清
- python中的流程控制语句:continue、break 和 return使用方法
- L017:continue和break - 教程文案
- 作为前端开发者,你都经历过怎样的面试?
- 面试被问 const 是否不可变?这样回答才显功底
- 标签列表
-
- git pull (33)
- git fetch (35)
- mysql insert (35)
- mysql distinct (37)
- concat_ws (36)
- java continue (36)
- jenkins官网 (37)
- mysql 子查询 (37)
- python元组 (33)
- mybatis 分页 (35)
- vba split (37)
- redis watch (34)
- python list sort (37)
- nvarchar2 (34)
- mysql not null (36)
- hmset (35)
- python telnet (35)
- python readlines() 方法 (36)
- munmap (35)
- docker network create (35)
- redis 集合 (37)
- python sftp (37)
- setpriority (34)
- c语言 switch (34)
- git commit (34)
