网站首页 > 技术文章 正文

介绍
PostgreSQL是一个开放源代码的对象关系数据库管理系统。PostgreSQL符合ACID且具有事务性。它具有触发器,外键并支持功能和存储过程。
PostgreSQL被Uber,Apple,Netflix和Instagram等巨头使用。
在本文中,我们将看到如何从Python Script连接到PostgreSQL并执行查询操作。
安装依赖环境:
使用python 3创建一个虚拟环境并激活它。安装以下软件包。
psycopg2==2.7.3.2
安装:
使用以下命令安装PostgreSQL数据库和实用程序。
$sudo apt-get update $sudo apt-get install postgresql postgresql-contrib
默认情况下,PostgreSQL在新安装时会设置用户和数据库“ postgres”。我们需要切换到该用户来使用postgres数据库。
$sudo -su postgres
现在通过在终端上输入psql进入Postgres提示符。
我们正在使用版本10.3。
如果在连接数据库时遇到任何错误,请确保PostgreSQL正在运行。使用以下命令检查状态。
$systemctl status postgresql
您可以使用以下命令检查日志中的错误。
$tail -f /var/log/postgresql
创建数据库:
在创建新数据库之前,让我们列出所有数据库。使用\l 或 \list相同。
要创建数据库,请键入 \q 退出psql终端,然后使用命令createdb testdb。
postgres@brahma:~$ createdb testdb postgres@brahma:~$ psql psql (10.3 (Ubuntu 10.3-1.pgdg16.04+1)) Type "help" for help. postgres=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges ---------------+----------+----------+---------+-------+----------------------- postgres | postgres | UTF8 | en_IN | en_IN | rana_test | postgres | UTF8 | en_IN | en_IN | template0 | postgres | UTF8 | en_IN | en_IN | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | en_IN | en_IN | =c/postgres + | | | | | postgres=CTc/postgres testdb | postgres | UTF8 | en_IN | en_IN | (5 rows) postgres=# \c testdb You are now connected to database "testdb" as user "postgres". testdb=#
创建表:
PostgreSQL中的大多数查询sytanx与MySQL相同。
create table users ( id serial PRIMARY KEY, username varchar (20) NOT NULL, age smallint NOT NULL, location varchar (50) NOT NULL );
将上述语法复制粘贴到终端中,将创建新表。您可以通过键入\ d列出表。
testdb=# create table users ( testdb(# username varchar (20) NOT NULL, testdb(# age smallint NOT NULL, testdb(# location varchar (50) NOT NULL testdb(# ); CREATE TABLE testdb=# \d List of relations Schema | Name | Type | Owner --------+-------+-------+---------- public | users | table | postgres (1 row) testdb=#
您可以通过访问官方网站了解有关从psql终端查询的更多信息。现在,让我们尝试使用Python代码连接PostgreSQL并执行操作。
从Python脚本连接:
我们在虚拟环境中安装了psycopg软件包。使用Python脚本中的以下代码连接到数据库。
import psycopg2 # this function will return the connection object def connect(): conn = None try: conn = psycopg2.connect(host="localhost", user="postgres", password="root", database="testdb") except Exception as e: print(repr(e)) return conn
将数据插入表中:
首先获取连接和游标,然后创建查询。执行查询后,使用连接提交并关闭游标和连接。
conn = connect() cur = conn.cursor() last_insert_id = None # inserting data in users table sql_query = "insert into users (username, age, location) values (%s, %s, %s) returning id;" sql_data = ( "Ajay", "25", "New York" ) cur.execute(sql_query, sql_data) last_insert_id = cur.fetchone()[0] print("Last Insert ID " + str(last_insert_id)) conn.commit() cur.close() conn.close() return last_insert_id
我们将数据插入表中并返回主键ID(即序列号)。
从表中获取数据:
PostgreSQL的选择查询与MySQL相同。
conn = connect() cur = conn.cursor() sql_query = "select username, age, location from users where location = %s;" sql_data = ("Delhi") cur.execute(sql_query, sql_data) results = cur.fetchall() return results
更新行:
conn = connect() cursor = conn.cursor() sql_query = "update users set location = %s where username = %s;" sql_data = ("Mumbai", "Ajay") cursor.execute(sql_query, sql_data) cursor.close() conn.close() return True
要退出终端,请使用\ q命令。
总结:
以上介绍了PostgreSQL的基本用法及环境搭建,并且使用简单的Python脚本对PostgreSQL进行了基础操作,希望对大家有所帮助。
猜你喜欢
- 2024-12-16 sqlserver 测试
- 2024-12-16 Python 读写Sqlserver数据库
- 2024-12-16 Python如何解析SQL语句并转换为Python对象,SQLParse类库的使用
- 2024-12-16 Star 4.7k!纯Python开发!自称目前最快的纯Python SQL解析器!
- 2024-12-16 Python 学习 第17篇:sqlalchemy读写SQL
- 2024-12-16 盘点一个通过python大批量插入数据到数据库的方法
- 2024-12-16 python如何操作SQL Server数据库?
- 2024-12-16 Mysql四:常用查询语句(十种),一般情况够用了
- 2024-12-16 Python操作Sqlserver数据库(单库异步执行:增删改查)
- 05-25Python 3.14 t-string 要来了,它与 f-string 有何不同?
- 05-25Python基础元素语法总结
- 05-25Python中的变量是什么东西?
- 05-25新手常见的python报错及解决方案
- 05-2511-Python变量
- 05-2510个每个人都是需要知道Python问题
- 05-25Python编程:轻松掌握函数定义、类型及其参数传递方式
- 05-25Python基础语法
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 90℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 81℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)