Python數(shù)據(jù)庫學習心得:SQLite、MySQL、PostgreSQL優(yōu)缺點
作者介紹了自己從非科班轉(zhuǎn)行學習Python與數(shù)據(jù)庫交互的心得,從SQLite、MySQL、PostPostPost等PostPostgreSQL等三種數(shù)據(jù)庫出發(fā),介紹了他們的基本概念、使用方法及其優(yōu)缺點,接著介紹了使用ORM框架如SQLAlchemy和Django ORMD和D以及連接池的使用,最后分享了學習心得、實踐項目項目建議和技巧D和和注意事項等并希望幫助同樣是非科班轉(zhuǎn)行者D學習數(shù)據(jù)庫交互
一、SQLite數(shù)據(jù)庫
1.1 SQLite簡介
SQLite是一個輕量級的嵌入式數(shù)據(jù)庫,它不需要單獨的服務器進程,數(shù)據(jù)存儲在一個文件中:
- 輕量級:核心庫很小,適合嵌入式應用
- 無需配置:不需要安裝和配置服務器
- 跨平臺:支持多種操作系統(tǒng)
- ACID兼容:支持原子性、一致性、隔離性、持久性
1.2 使用sqlite3模塊
Python內(nèi)置了sqlite3模塊,可以直接與SQLite數(shù)據(jù)庫交互:
import sqlite3
# 連接到SQLite數(shù)據(jù)庫
# 如果數(shù)據(jù)庫不存在,會自動創(chuàng)建
conn = sqlite3.connect('example.db')
# 創(chuàng)建游標
cursor = conn.cursor()
# 創(chuàng)建表
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
email TEXT UNIQUE
)
''')
# 插入數(shù)據(jù)
cursor.execute("INSERT INTO users (name, age, email) VALUES (?, ?, ?)", ('Alice', 25, 'alice@example.com'))
cursor.execute("INSERT INTO users (name, age, email) VALUES (?, ?, ?)", ('Bob', 30, 'bob@example.com'))
# 提交事務
conn.commit()
# 查詢數(shù)據(jù)
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
# 更新數(shù)據(jù)
cursor.execute("UPDATE users SET age = ? WHERE name = ?", (26, 'Alice'))
conn.commit()
# 刪除數(shù)據(jù)
cursor.execute("DELETE FROM users WHERE name = ?", ('Bob',))
conn.commit()
# 關閉連接
conn.close()
1.3 使用SQLite的優(yōu)勢
- 無需安裝:Python內(nèi)置支持
- 易于使用:API簡單直觀
- 適合小型應用:適合數(shù)據(jù)量不大的應用
- 便于測試:適合單元測試和集成測試
二、MySQL數(shù)據(jù)庫
2.1 MySQL簡介
MySQL是一個流行的關系型數(shù)據(jù)庫管理系統(tǒng):
- 功能強大:支持復雜的SQL語句和事務
- 可擴展性:適合大型應用
- 社區(qū)活躍:有龐大的社區(qū)支持
- 開源免費:開源軟件,免費使用
2.2 使用pymysql庫
需要安裝pymysql庫來與MySQL數(shù)據(jù)庫交互:
# 安裝pymysql
# pip install pymysql
import pymysql
# 連接到MySQL數(shù)據(jù)庫
conn = pymysql.connect(
host='localhost',
user='root',
password='password',
database='test',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
# 創(chuàng)建游標
cursor = conn.cursor()
# 創(chuàng)建表
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT,
email VARCHAR(255) UNIQUE
)
''')
# 插入數(shù)據(jù)
cursor.execute("INSERT INTO users (name, age, email) VALUES (%s, %s, %s)", ('Alice', 25, 'alice@example.com'))
cursor.execute("INSERT INTO users (name, age, email) VALUES (%s, %s, %s)", ('Bob', 30, 'bob@example.com'))
# 提交事務
conn.commit()
# 查詢數(shù)據(jù)
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
# 更新數(shù)據(jù)
cursor.execute("UPDATE users SET age = %s WHERE name = %s", (26, 'Alice'))
conn.commit()
# 刪除數(shù)據(jù)
cursor.execute("DELETE FROM users WHERE name = %s", ('Bob',))
conn.commit()
# 關閉連接
conn.close()
2.3 使用MySQL的優(yōu)勢
- 適合大型應用:支持高并發(fā)和大數(shù)據(jù)量
- 功能豐富:支持復雜的SQL語句和存儲過程
- 生態(tài)成熟:有豐富的工具和庫
- 社區(qū)支持:有龐大的社區(qū)和文檔
三、PostgreSQL數(shù)據(jù)庫
3.1 PostgreSQL簡介
PostgreSQL是一個功能強大的開源關系型數(shù)據(jù)庫:
- 高級特性:支持復雜的數(shù)據(jù)類型和查詢
- 可擴展性:支持自定義數(shù)據(jù)類型和函數(shù)
- 可靠性:具有強大的事務支持和數(shù)據(jù)完整性
- 開源免費:開源軟件,免費使用
3.2 使用psycopg2庫
需要安裝psycopg2庫來與PostgreSQL數(shù)據(jù)庫交互:
# 安裝psycopg2
# pip install psycopg2-binary
import psycopg2
# 連接到PostgreSQL數(shù)據(jù)庫
conn = psycopg2.connect(
host='localhost',
user='postgres',
password='password',
database='test',
port=5432
)
# 創(chuàng)建游標
cursor = conn.cursor()
# 創(chuàng)建表
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INTEGER,
email VARCHAR(255) UNIQUE
)
''')
# 插入數(shù)據(jù)
cursor.execute("INSERT INTO users (name, age, email) VALUES (%s, %s, %s)", ('Alice', 25, 'alice@example.com'))
cursor.execute("INSERT INTO users (name, age, email) VALUES (%s, %s, %s)", ('Bob', 30, 'bob@example.com'))
# 提交事務
conn.commit()
# 查詢數(shù)據(jù)
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
# 更新數(shù)據(jù)
cursor.execute("UPDATE users SET age = %s WHERE name = %s", (26, 'Alice'))
conn.commit()
# 刪除數(shù)據(jù)
cursor.execute("DELETE FROM users WHERE name = %s", ('Bob',))
conn.commit()
# 關閉連接
conn.close()
3.3 使用PostgreSQL的優(yōu)勢
- 高級特性:支持JSON、數(shù)組等復雜數(shù)據(jù)類型
- 可擴展性:支持自定義數(shù)據(jù)類型和函數(shù)
- 可靠性:具有強大的事務支持和數(shù)據(jù)完整性
- 安全性:具有強大的安全特性
四、使用ORM框架
4.1 SQLAlchemy
SQLAlchemy是一個流行的Python ORM框架:
# 安裝SQLAlchemy
# pip install SQLAlchemy
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 創(chuàng)建數(shù)據(jù)庫引擎
# SQLite
engine = create_engine('sqlite:///example.db')
# MySQL
# engine = create_engine('mysql+pymysql://root:password@localhost/test')
# PostgreSQL
# engine = create_engine('postgresql://postgres:password@localhost/test')
# 創(chuàng)建基類
Base = declarative_base()
# 定義模型
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(255), nullable=False)
age = Column(Integer)
email = Column(String(255), unique=True)
# 創(chuàng)建表
Base.metadata.create_all(engine)
# 創(chuàng)建會話
Session = sessionmaker(bind=engine)
session = Session()
# 插入數(shù)據(jù)
user1 = User(name='Alice', age=25, email='alice@example.com')
user2 = User(name='Bob', age=30, email='bob@example.com')
session.add(user1)
session.add(user2)
session.commit()
# 查詢數(shù)據(jù)
users = session.query(User).all()
for user in users:
print(user.id, user.name, user.age, user.email)
# 更新數(shù)據(jù)
user = session.query(User).filter_by(name='Alice').first()
user.age = 26
session.commit()
# 刪除數(shù)據(jù)
user = session.query(User).filter_by(name='Bob').first()
session.delete(user)
session.commit()
# 關閉會話
session.close()
4.2 Django ORM
Django ORM是Django框架內(nèi)置的ORM:
# models.py
from django.db import models
class User(models.Model):
name = models.CharField(max_length=255)
age = models.IntegerField()
email = models.EmailField(unique=True)
def __str__(self):
return self.name
# 使用Django ORM
# 創(chuàng)建用戶
user = User.objects.create(name='Alice', age=25, email='alice@example.com')
# 查詢用戶
users = User.objects.all()
for user in users:
print(user)
# 更新用戶
user = User.objects.get(name='Alice')
user.age = 26
user.save()
# 刪除用戶
user = User.objects.get(name='Alice')
user.delete()
五、數(shù)據(jù)庫連接池
5.1 使用連接池
對于高并發(fā)應用,使用連接池可以提高性能:
# 安裝SQLAlchemy
# pip install SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import QueuePool
# 創(chuàng)建帶有連接池的引擎
engine = create_engine(
'mysql+pymysql://root:password@localhost/test',
poolclass=QueuePool,
pool_size=10,
max_overflow=20,
pool_pre_ping=True
)
# 創(chuàng)建會話
Session = sessionmaker(bind=engine)
session = Session()
# 使用會話
# ...
# 關閉會話
session.close()
六、Python與Rust的對比
作為一個同時學習Python和Rust的轉(zhuǎn)碼者,我發(fā)現(xiàn)對比學習是一種很好的方法:
6.1 數(shù)據(jù)庫交互對比
- Python:有豐富的數(shù)據(jù)庫驅(qū)動和ORM框架
- Rust:有diesel、sqlx等ORM框架
- 開發(fā)效率:Python開發(fā)效率高,Rust開發(fā)效率相對較低
- 性能:Rust性能優(yōu)異,Python性能相對較低
6.2 學習心得
- Python的優(yōu)勢:開發(fā)效率高,生態(tài)豐富
- Rust的優(yōu)勢:性能優(yōu)異,內(nèi)存安全
- 相互借鑒:從Python學習快速開發(fā),從Rust學習性能優(yōu)化
七、實踐項目推薦
7.1 數(shù)據(jù)庫項目
- 用戶管理系統(tǒng):實現(xiàn)用戶的增刪改查
- 博客系統(tǒng):實現(xiàn)文章的發(fā)布和管理
- 電商系統(tǒng):實現(xiàn)商品和訂單的管理
- 數(shù)據(jù)分析系統(tǒng):實現(xiàn)數(shù)據(jù)的存儲和分析
八、學習方法和技巧
8.1 學習方法
- 循序漸進:先學習基礎的數(shù)據(jù)庫操作,再學習高級特性
- 項目實踐:通過實際項目來鞏固知識
- 文檔閱讀:仔細閱讀數(shù)據(jù)庫和ORM框架的官方文檔
- 社區(qū)交流:加入社區(qū),向他人學習
8.2 常見問題和解決方法
- 連接問題:檢查數(shù)據(jù)庫服務是否運行,連接參數(shù)是否正確
- 性能問題:使用索引,優(yōu)化SQL語句,使用連接池
- 安全問題:使用參數(shù)化查詢,避免SQL注入
- 數(shù)據(jù)一致性:使用事務,確保數(shù)據(jù)的一致性
九、總結(jié)
Python與數(shù)據(jù)庫的交互是編程中非常重要的一部分。作為一個非科班轉(zhuǎn)碼者,我深刻體會到學習數(shù)據(jù)庫的重要性。
我的學習過程并不是一帆風順的,遇到了很多困難和挫折,但通過不斷地實踐和學習,我逐漸掌握了Python與數(shù)據(jù)庫交互的各種技巧。
到此這篇關于Python數(shù)據(jù)庫學習心得:SQLite、MySQL、PostgreSQL優(yōu)缺點的文章就介紹到這了,更多相關Python數(shù)據(jù)庫:SQLite、MySQL、PostgreSQL內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Python連接數(shù)據(jù)庫的3種方法對比(SQLite\MySQL\PostgreSQL)
- 在Python中使用SQLite數(shù)據(jù)庫進行增刪改查操作的代碼示例
- python連接sqlite3簡單用法完整例子
- Python中如何使用sqlite3操作SQLite數(shù)據(jù)庫詳解
- 利用Python連接MySQL超詳細實戰(zhàn)教程
- Python進行SQLite和MySQL數(shù)據(jù)庫連接與操作的完整指南
- Python進行PostgreSQL數(shù)據(jù)庫連接的詳細使用指南
- 使用python進行PostgreSQL數(shù)據(jù)庫連接全過程
- Python連接PostgreSQL數(shù)據(jù)庫并查詢數(shù)據(jù)的詳細指南
- Python連接到PostgreSQL數(shù)據(jù)庫的方法詳解
相關文章
使用FastAPI構建高性能RESTful API的完整指南
FastAPI是一個現(xiàn)代、高性能的Python Web框架,專為構建API而設計,本指南將帶你從基礎到高級,全面掌握FastAPI的使用,感興趣的小伙伴跟隨小編一起學習一下吧2025-11-11

