Python 入門 psycopg2-PostgreSQL


本教程中,我們將學習如何使用 PostgreSQL 和 Python。應在學習本教程前安裝特定內容。我們來安裝它們。

根據 指南 安裝 PostgreSQL

安裝用於連線和使用 PostgreSQL 的 Python 模組 psycopg2。執行命令以安裝它。

pip install psycopg2

現在,開啟 pgAdmin。並建立一個示例資料庫。接下來,按照以下步驟開始資料庫操作。

  • 匯入 psycopg2 模組。
  • 將資料庫名稱、使用者名稱和密碼儲存在不同的變數中。
  • 使用 psycopg2.connect(database=name, user=name, password=password) 方法建立到資料庫的連線。
  • 例項化一個遊標物件以執行 SQL 命令。
  • 使用 cursor.execute(query) 方法建立查詢並執行它們。
  • 而且,使用 cursor.fetchall() 方法獲取資訊(如果可用)。
  • 使用 connection.close() 方法關閉連線。

示例

# importing the psycopg2 module
import psycopg2
# storing all the information
database = 'testing'
user = 'postgres'
password = 'C&o%Z?bc'
# connecting to the database
connection = psycopg2.connect(database=database, user=user, password=password)
# instantiating the cursor
cursor = connection.cursor()
# query to create a table
create_table = "CREATE TABLE testing_members (id SERIAL PRIMARY KEY, name VARCH
25) NOT NULL)"
# executing the query
cursor.execute(create_table)
# sample data to populate the database table
testing_members = ['Python', 'C', 'JavaScript', 'React', 'Django']
# query to populate the table testing_members
for testing_member in testing_members:
   populate_db = f"INSERT INTO testing_members (name) VALUES ('{testing_member
   cursor.execute(populate_db)
   # saving the changes to the database
   connection.commit()
   # query to fetch all
   fetch_all = "SELECT * FROM testing_members"
   cursor.execute(fetch_all)
   # fetching all the rows
   rows = cursor.fetchall()
   # printing the data
   for row in rows:
      print(f"{row[0]} {row[1]}")
      # closing the connection
      connection.close()

輸出

如果您執行上述程式碼,將會得到以下結果。

1 Python
2 C
3 JavaScript
4 React
5 Django

結論

如果對本教程有任何疑問,敬請在評論區中提出。

更新於:2020 年 7 月 7 日

698 次瀏覽

開始您的 職業生涯

透過完成課程獲得認證

開始
廣告