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

SQL กับ Python และ SQLite

Python มีโมดูล sqlite3 ติดมาสำหรับเชื่อมต่อ SQLite database

ขั้นตอนการเชื่อมต่อ

  1. Import sqlite3
  2. สร้าง connection: conn = sqlite3.connect("db_name")
  3. สร้าง cursor: cursor = conn.cursor()

สร้างตารางและเพิ่มข้อมูล

import sqlite3

conn = sqlite3.connect("tutorialspoint.db")
cursor = conn.cursor()

create_table_sql = """
CREATE TABLE students (
    id INTEGER PRIMARY KEY,
    first_name VARCHAR(20),
    last_name VARCHAR(30),
    gender CHAR(1)
);
"""
cursor.execute(create_table_sql)

cursor.execute('INSERT INTO students VALUES (1, "John", "Hill", "M");')
cursor.execute('INSERT INTO students VALUES (2, "Jessy", "Hill", "F");')
cursor.execute('INSERT INTO students VALUES (3, "Antony", "Hill", "M");')

conn.commit()
conn.close()

Query ข้อมูล

conn = sqlite3.connect("tutorialspoint.db")
cursor = conn.cursor()

cursor.execute("SELECT * FROM students;")
students = cursor.fetchall()
print(students)
# [(1, 'John', 'Hill', 'M'), (2, 'Jessy', 'Hill', 'F'), (3, 'Antony', 'Hill', 'M')]

conn.close()

สรุป

sqlite3 ใช้งานง่าย ไม่ต้องติดตั้ง server แยก เหมาะสำหรับแอปเล็กหรือทดสอบ