Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เขียนโปรแกรม Python อ่านข้อมูลจากฐานข้อมูล SQLite

สมมติว่าคุณมีฐานข้อมูล SQLite และต้องการอ่านข้อมูลจากตารางเข้า DataFrame

วิธีแก้ปัญหา

  1. เชื่อมต่อฐานข้อมูลด้วย sqlite3.connect('db.sqlite3')
  2. ใช้ pd.read_sql_query() อ่านข้อมูลด้วย SQL query
  3. ปิด connection หลังใช้งาน

ตัวอย่างโค้ด

import pandas as pd
import sqlite3

# เชื่อมต่อฐานข้อมูล SQLite
con = sqlite3.connect("db.sqlite3")

# อ่านข้อมูลจากตาราง student
df = pd.read_sql_query("SELECT * FROM student", con)

print("ข้อมูลจากฐานข้อมูล:")
print(df)

# ปิด connection
con.close()

ผลลัพธ์ตัวอย่าง

ข้อมูลจากฐานข้อมูล:
   Id   Name
0   1  stud1
1   2  stud2
2   3  stud3
3   4  stud4
4   5  stud5

คำอธิบาย:

  • sqlite3.connect() สร้าง connection object ไปยังไฟล์ฐานข้อมูล
  • pd.read_sql_query(sql, con) รัน SQL query และคืนค่า DataFrame โดยตรง
  • รองรับ SQL ทุกประเภท: SELECT, JOIN, WHERE, GROUP BY, etc.
  • ควรใช้ context manager: with sqlite3.connect(...) as con: เพื่อปิด connection อัตโนมัติ
  • สำหรับฐานข้อมูลอื่น (PostgreSQL, MySQL) ใช้ SQLAlchemy engine แทน