設為首頁收藏本站

艾歐踢論壇

 找回密碼
 立即註冊

QQ登錄

只需一步,快速開始

搜索
熱搜: 活動 交友 discuz
查看: 253|回復: 0
打印 上一主題 下一主題

如何與資料庫連接

[複製鏈接]
跳轉到指定樓層
樓主
發表於 2023-4-14 08:35:19 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
要連接 MySQL 或 PostgreSQL 資料庫,我們不需要自己重寫。這邊會用到兩個套件,一個是連接 MySQL 用的套件 pymysql、另一個是 PostgreSQL 用的套件 psycopg2。除了套件外,會在著重介紹一套 ORM(Object Relational Mapping)服務 SQLAlchemySQLAlchemy 可以與 MySQL、PostgreSQL 連接外,還有不需要直接撰寫 SQL 語法的好處。
  1. # 範例程式
  2. import pymysql.cursors

  3. # Connect to the database
  4. connection = pymysql.connect(host='localhost',  # 你伺服器/主機
  5.                              user='user',       # 你資料庫的帳號
  6.                              password='password', # 你資料庫的密碼
  7.                              database='db',     # 你資料庫的名稱
  8.                              cursorclass=pymysql.cursors.DictCursor)

  9. with connection:
  10.     with connection.cursor() as cursor:
  11.         # Create a new record
  12.         sql = "INSERT INTO `users` (`name`, `email`, `company`) VALUES (%s, %s, %s)"
  13.         cursor.execute(sql, ('Anonymous', 'itisa@sample.code', 'famous-company'))

  14.     # connection is not autocommit by default. So you must commit to save
  15.     # your changes.
  16.     connection.commit()

  17.     with connection.cursor() as cursor:
  18.         # Read a single record
  19.         sql = "SELECT `id`, `company` FROM `users` WHERE `email`=%s"
  20.         cursor.execute(sql, ('itisa@sample.code',))
  21.         result = cursor.fetchone()
  22.         print(result)
複製代碼
  1. import psycopg2

  2. # Connect to your postgres DB
  3. conn = psycopg2.connect("dbname=test user=postgres password=secret") # 亦或是 dbname="test", user="postgres", password="secret"

  4. # Open a cursor to perform database operations
  5. cur = conn.cursor()

  6. cur.execute("""
  7.     INSERT INTO users (name, email, company)
  8.     VALUES (%s, %s, %s);
  9.     """,
  10.     ("Hermit", "itissecond@sample.code", "best-company"))

  11. # Execute a query
  12. cur.execute("SELECT * FROM")

  13. # Retrieve query results
  14. records = cur.fetchall()

  15. # Make the changes to the database persistent
  16. conn.commit()

  17. # Close communication with the database
  18. cur.close()
  19. conn.close()
複製代碼
SQLAlchemy
SQLAlchemy 是一個 Python 操作資料庫的工具,基本上可以分成三個部分:
  • DBAPI
  • SQLAlchemy Core
  • SQLAlchemy Object Relation Mapping (ORM)
下圖是 SQLAlchemy 框架的各個元件組成:
  • Engine:框架引擎
  • Connection Pooling:資料庫連結池
  • Dialect:資料庫DB API種類
  • Schema/Types:架構&型別
  • SQL Exprression Language:SQL表示式語言
ORM 可以想成是透過 Python 產生的一張資料庫地圖,用於與資料庫溝通、操作的工具。ORM 這個機制除了將資料庫的資料轉成物件外,大部分的資料庫操作都可以透過物件去實現,例如建立、新增、刪除等,甚至是建立資料表之間的關聯也可以用物件實作。在開始寫 ORM 前,不免俗還是要安裝套件。
  1. from sqlalchemy.ext.declarative import declarative_base
  2. from sqlalchemy import Column, Integer, String, create_engine
  3. from sqlalchemy.orm import sessionmaker

  4. # 宣告對映
  5. Base = declarative_base()

  6. class User(Base):  # 建議放到 models.py 裡
  7.     __tablename__ = 'users'
  8.     id = Column(Integer, primary_key=True)
  9.     name = Column(String(50), nullable=False)
  10.     email = Column(String(50), nullable=False)
  11.     company = Column(String(50), nullable=False)

  12. engine = create_engine('postgresql://postgres:secret@localhost:5432/test', echo=True, future=True) # MySQL 的連接方式 'mysql+mysqlconnector://user:password@localhost:3306/test'

  13. Session = sessionmaker(bind=engine)
  14. session = Session()

  15. session.add(User(name='ed', email='ormtest@gooogle', company='Gooogle'))
  16. person = session.query(User).filter_by(name='ed').first()

  17. session.commit()

  18. print('Who is: ', person)
複製代碼
實務上資料庫的使用者密碼資訊 ,  configuration 與 environment variables,將敏感的資料放在 .env file 裡, 不 直接放在明碼.


分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏 轉播轉播 分享分享 分享淘帖
回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|Archiver|手機版|艾歐踢創新工坊    

GMT+8, 2024-5-17 00:27 , Processed in 0.281814 second(s), 19 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表