การเชื่อมต่อกับฐานข้อมูล

Python เบื้องต้นสำหรับฐานข้อมูล

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

รู้จัก SQLAlchemy

  • สองส่วนหลัก
    • Core (เน้น Relational Model)
    • ORM (เน้น User Data Model)
Python เบื้องต้นสำหรับฐานข้อมูล

ฐานข้อมูลมีหลายประเภท

  • SQLite
  • PostgreSQL
  • MySQL
  • Microsoft SQL Server
  • Oracle SQL
  • และอื่น ๆ อีกมาก
Python เบื้องต้นสำหรับฐานข้อมูล

การเชื่อมต่อกับฐานข้อมูล

from sqlalchemy import create_engine

engine = create_engine('sqlite:///census_nyc.sqlite')
connection = engine.connect()
  • Engine: อินเทอร์เฟซหลักสำหรับเชื่อมต่อกับฐานข้อมูลผ่าน SQLAlchemy
  • Connection string: ข้อมูลทั้งหมดที่จำเป็นสำหรับค้นหาฐานข้อมูล (รวมถึงข้อมูลล็อกอิน หากจำเป็น)
Python เบื้องต้นสำหรับฐานข้อมูล

ว่าด้วย Connection String

driverdialect.png

        Driver + Dialect

Python เบื้องต้นสำหรับฐานข้อมูล

ว่าด้วย Connection String

filename.png

                                                                                               Filename

Python เบื้องต้นสำหรับฐานข้อมูล

ฐานข้อมูลมีอะไรอยู่บ้าง?

ก่อนจะ query ฐานข้อมูล ควรตรวจสอบก่อนว่ามีข้อมูลอะไรอยู่บ้าง เช่น ดูรายชื่อตาราง:

from sqlalchemy import create_engine

engine = create_engine('sqlite:///census_nyc.sqlite')
print(engine.table_names())
['census', 'state_fact']
Python เบื้องต้นสำหรับฐานข้อมูล

Reflection

Reflection จะอ่านฐานข้อมูลและสร้างออบเจกต์ Table ของ SQLAlchemy

from sqlalchemy import MetaData, Table

metadata = MetaData()
census = Table('census', metadata, autoload=True, autoload_with=engine)
print(repr(census))
Table('census', MetaData(bind=None), Column('state', VARCHAR(
length=30), table=<census>), Column('sex', VARCHAR(length=1),
table=<census>), Column('age', INTEGER(), table=<census>),
Column('pop2000', INTEGER(), table=<census>), Column('pop2008',
INTEGER(), table=<census>), schema=None)
Python เบื้องต้นสำหรับฐานข้อมูล

มาฝึกกันเถอะ!

Python เบื้องต้นสำหรับฐานข้อมูล

Preparing Video For Download...