要連接 MySQL 或 PostgreSQL 資料庫,我們不需要自己重寫。這邊會用到兩個套件,一個是連接 MySQL 用的套件 pymysql、另一個是 PostgreSQL 用的套件 psycopg2。除了套件外,會在著重介紹一套 ORM(Object Relational Mapping)服務 SQLAlchemy, SQLAlchemy 可以與 MySQL、PostgreSQL 連接外,還有不需要直接撰寫 SQL 語法的好處。
- # 範例程式
- import pymysql.cursors
- # Connect to the database
- connection = pymysql.connect(host='localhost', # 你伺服器/主機
- user='user', # 你資料庫的帳號
- password='password', # 你資料庫的密碼
- database='db', # 你資料庫的名稱
- cursorclass=pymysql.cursors.DictCursor)
- with connection:
- with connection.cursor() as cursor:
- # Create a new record
- sql = "INSERT INTO `users` (`name`, `email`, `company`) VALUES (%s, %s, %s)"
- cursor.execute(sql, ('Anonymous', 'itisa@sample.code', 'famous-company'))
- # connection is not autocommit by default. So you must commit to save
- # your changes.
- connection.commit()
- with connection.cursor() as cursor:
- # Read a single record
- sql = "SELECT `id`, `company` FROM `users` WHERE `email`=%s"
- cursor.execute(sql, ('itisa@sample.code',))
- result = cursor.fetchone()
- print(result)
複製代碼- import psycopg2
- # Connect to your postgres DB
- conn = psycopg2.connect("dbname=test user=postgres password=secret") # 亦或是 dbname="test", user="postgres", password="secret"
- # Open a cursor to perform database operations
- cur = conn.cursor()
- cur.execute("""
- INSERT INTO users (name, email, company)
- VALUES (%s, %s, %s);
- """,
- ("Hermit", "itissecond@sample.code", "best-company"))
- # Execute a query
- cur.execute("SELECT * FROM")
- # Retrieve query results
- records = cur.fetchall()
- # Make the changes to the database persistent
- conn.commit()
- # Close communication with the database
- cur.close()
- 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 前,不免俗還是要安裝套件。 - from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy import Column, Integer, String, create_engine
- from sqlalchemy.orm import sessionmaker
- # 宣告對映
- Base = declarative_base()
- class User(Base): # 建議放到 models.py 裡
- __tablename__ = 'users'
- id = Column(Integer, primary_key=True)
- name = Column(String(50), nullable=False)
- email = Column(String(50), nullable=False)
- company = Column(String(50), nullable=False)
- engine = create_engine('postgresql://postgres:secret@localhost:5432/test', echo=True, future=True) # MySQL 的連接方式 'mysql+mysqlconnector://user:password@localhost:3306/test'
- Session = sessionmaker(bind=engine)
- session = Session()
- session.add(User(name='ed', email='ormtest@gooogle', company='Gooogle'))
- person = session.query(User).filter_by(name='ed').first()
- session.commit()
- print('Who is: ', person)
複製代碼實務上資料庫的使用者密碼資訊 , configuration 與 environment variables,將敏感的資料放在 .env file 裡, 不 直接放在明碼.
|