在Python中使用PostgreSQL數據庫

在Python中使用PostgreSQL數據庫

介紹

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進行了基礎操作,希望對大家有所幫助。


分享到:


相關文章: