程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

在Python中使用PostgreSQL数据库

hfteth 2024-12-16 13:21:23 技术文章 14 ℃

介绍

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进行了基础操作,希望对大家有所帮助。

Tags:

最近发表
标签列表