欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python數(shù)據(jù)庫自動化完整指南

 更新時間:2025年03月26日 08:38:23   作者:老胖閑聊  
本指南詳細講解如何使用Python操作MySQL、Oracle和Microsoft?SQL?Server數(shù)據(jù)庫,涵蓋常用庫、基礎(chǔ)操作、高級功能及完整代碼示例,需要的朋友可以參考下

一、MySQL 操作詳解

1. 常用庫

  • mysql-connector-python(官方驅(qū)動)
    安裝:pip install mysql-connector-python
  • PyMySQL(純 Python 實現(xiàn))
    安裝:pip install pymysql

2. 基礎(chǔ)操作

連接數(shù)據(jù)庫

import mysql.connector

config = {
    'user': 'root',
    'password': '123456',
    'host': 'localhost',
    'database': 'test_db'
}
conn = mysql.connector.connect(**config)
cursor = conn.cursor()

執(zhí)行 SQL

# 創(chuàng)建表
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255),
    email VARCHAR(255)
)
""")

# 插入數(shù)據(jù)
cursor.execute("INSERT INTO users (name, email) VALUES (%s, %s)", ('Alice', 'alice@example.com'))
conn.commit()

3. 高級功能

事務(wù)管理

try:
    cursor.execute("INSERT INTO users (name) VALUES ('Bob')")
    cursor.execute("UPDATE users SET email='error' WHERE id=999")  # 模擬錯誤
    conn.commit()
except mysql.connector.Error as e:
    conn.rollback()

二、Oracle 操作詳解

1. 常用庫

2. 基礎(chǔ)操作

連接數(shù)據(jù)庫

import cx_Oracle

dsn = cx_Oracle.makedsn("localhost", 1521, service_name="ORCLCDB")
conn = cx_Oracle.connect(user="scott", password="tiger", dsn=dsn)
cursor = conn.cursor()

執(zhí)行 SQL

# 使用序列插入數(shù)據(jù)
cursor.execute("CREATE SEQUENCE user_seq START WITH 1 INCREMENT BY 1")
cursor.execute("""
INSERT INTO users (id, name) 
VALUES (user_seq.NEXTVAL, :name)""", name="Charlie")
conn.commit()

3. 高級功能

調(diào)用存儲過程

p_name = cursor.var(str)
cursor.callproc("get_user", [1, p_name])
print(p_name.getvalue())  # 輸出結(jié)果

三、Microsoft SQL Server 操作詳解

1. 常用庫

  • pyodbc(推薦)
    安裝:pip install pyodbc
    依賴:需安裝 ODBC Driver
  • pymssql(輕量級)
    安裝:pip install pymssql

2. 基礎(chǔ)操作

連接數(shù)據(jù)庫

import pyodbc

conn = pyodbc.connect(
    Driver='{ODBC Driver 17 for SQL Server}',
    Server='localhost',
    Database='test_db',
    UID='sa',
    PWD='password'
)
cursor = conn.cursor()

執(zhí)行 SQL

# 分頁查詢(OFFSET FETCH)
cursor.execute("""
SELECT * FROM users
ORDER BY id
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY
""")
print(cursor.fetchall())

3. 高級功能

批量插入

data = [('David', 'david@example.com'), ('Eva', 'eva@example.com')]
cursor.executemany("INSERT INTO users (name, email) VALUES (?, ?)", data)
conn.commit()

四、通用注意事項

1. 安全與性能

  • 參數(shù)化查詢:始終使用占位符(%s、?:name)避免 SQL 注入。
  • 連接管理:使用 with 上下文管理器或封裝類確保連接關(guān)閉。
# 示例:MySQL 上下文管理器
with mysql.connector.connect(**config) as conn:
    with conn.cursor() as cursor:
        cursor.execute("SELECT 1")

2. 異常處理

try:
    conn = cx_Oracle.connect("invalid_connection")
except cx_Oracle.DatabaseError as e:
    error = e.args[0]
    print(f"Code: {error.code}, Message: {error.message}")
finally:
    if conn:
        conn.close()

3. 自動化封裝類

class DatabaseAutomator:
    """通用數(shù)據(jù)庫操作封裝"""
    def __init__(self, db_type, **config):
        self.db_type = db_type
        self.config = config
        self.conn = None

    def __enter__(self):
        if self.db_type == "mysql":
            self.conn = mysql.connector.connect(**self.config)
        elif self.db_type == "oracle":
            dsn = cx_Oracle.makedsn(**self.config)
            self.conn = cx_Oracle.connect(user=self.config['user'], password=self.config['password'], dsn=dsn)
        # 其他數(shù)據(jù)庫類似
        return self.conn.cursor()

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.conn:
            if exc_type: self.conn.rollback()
            else: self.conn.commit()
            self.conn.close()

# 使用示例
with DatabaseAutomator("mysql", user="root", password="123456", host="localhost", database="test_db") as cursor:
    cursor.execute("SELECT * FROM users")

4. ORM 集成

  • SQLAlchemy 統(tǒng)一操作不同數(shù)據(jù)庫:
from sqlalchemy import create_engine

# MySQL
engine = create_engine("mysql+pymysql://user:password@localhost/db")

# Oracle
engine = create_engine("oracle+cx_oracle://user:password@localhost:1521/ORCLCDB")

# SQL Server
engine = create_engine("mssql+pyodbc://user:password@localhost/db?driver=ODBC+Driver+17+for+SQL+Server")

with engine.connect() as conn:
    result = conn.execute("SELECT * FROM users")
    print(result.fetchall())

通過本文檔,可快速掌握 Python 操作三大主流數(shù)據(jù)庫的核心方法。根據(jù)場景選擇合適的庫和工具,結(jié)合 ORM 框架可進一步提升開發(fā)效率。

到此這篇關(guān)于Python數(shù)據(jù)庫自動化完整指南的文章就介紹到這了,更多相關(guān)Python數(shù)據(jù)庫自動化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論