成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Python 封裝 MySQL 操作

開(kāi)發(fā) 前端
封裝 MySQL 操作可以讓你的代碼更加模塊化、可重用,并且更容易維護(hù)。通過(guò)封裝,你可以將與數(shù)據(jù)庫(kù)交互的細(xì)節(jié)隱藏起來(lái),對(duì)外提供一個(gè)簡(jiǎn)潔的接口。

前言

封裝 MySQL 操作可以讓你的代碼更加模塊化、可重用,并且更容易維護(hù)。通過(guò)封裝,你可以將與數(shù)據(jù)庫(kù)交互的細(xì)節(jié)隱藏起來(lái),對(duì)外提供一個(gè)簡(jiǎn)潔的接口。

完整代碼

import mysql.connector
from mysql.connector import Error
class MySQLWrapper:
    def __init__(self, host, user, password, database):
        """初始化數(shù)據(jù)庫(kù)連接參數(shù)。"""
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.connection = None
    def connect(self):
        """連接到 MySQL 數(shù)據(jù)庫(kù)。"""
        try:
            self.connection = mysql.connector.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                database=self.database
            )
            if self.connection.is_connected():
                db_info = self.connection.get_server_info()
                print(f"Connected to MySQL Server version {db_info}")
        except Error as e:
            print(f"Error while connecting to MySQL: {e}")
            self.connection = None
    def close(self):
        """關(guān)閉數(shù)據(jù)庫(kù)連接。"""
        if self.connection and self.connection.is_connected():
            self.connection.close()
            print("MySQL connection is closed.")
    def execute_query(self, query, values=None, commit=False):
        """執(zhí)行 SQL 語(yǔ)句,并根據(jù)需要返回結(jié)果或提交更改。"""
        if not self.connection or not self.connection.is_connected():
            print("Database connection is not established.")
            return None
        cursor = self.connection.cursor()
        try:
            if values:
                cursor.execute(query, values)
            else:
                cursor.execute(query)
            if commit:
                self.connection.commit()
            # 如果是 SELECT 查詢(xún),返回結(jié)果
            if query.strip().upper().startswith('SELECT'):
                return cursor.fetchall()
            else:
                return cursor.rowcount
        except Error as e:
            print(f"Error executing SQL: {e}")
            return None
        finally:
            cursor.close()
    def query_data(self, query, values=None):
        """執(zhí)行查詢(xún)操作。"""
        return self.execute_query(query, values, commit=False)
    def insert_data(self, query, values):
        """執(zhí)行插入操作。"""
        return self.execute_query(query, values, commit=True)
    def update_data(self, query, values):
        """執(zhí)行更新操作。"""
        return self.execute_query(query, values, commit=True)
    def delete_data(self, query, values):
        """執(zhí)行刪除操作。"""
        return self.execute_query(query, values, commit=True)
def main():
    # 創(chuàng)建 MySQLWrapper 實(shí)例并連接到數(shù)據(jù)庫(kù)
    db = MySQLWrapper(host='localhost', user='root', password='password', database='testdb')
    db.connect()
    if db.connection is not None:
        # 查詢(xún)數(shù)據(jù)
        query = "SELECT * FROM users WHERE age > %s"
        results = db.query_data(query, (18,))
        print("Query Results:")
        for row in results:
            print(row)
        # 插入數(shù)據(jù)
        insert_query = "INSERT INTO users (name, age) VALUES (%s, %s)"
        insert_values = ("John Doe", 25)
        rows_affected = db.insert_data(insert_query, insert_values)
        print(f"Insert affected {rows_affected} rows.")
        # 更新數(shù)據(jù)
        update_query = "UPDATE users SET age = %s WHERE name = %s"
        update_values = (26, "John Doe")
        rows_affected = db.update_data(update_query, update_values)
        print(f"Update affected {rows_affected} rows.")
        # 刪除數(shù)據(jù)
        delete_query = "DELETE FROM users WHERE name = %s"
        delete_values = ("John Doe",)
        rows_affected = db.delete_data(delete_query, delete_values)
        print(f"Delete affected {rows_affected} rows.")
        # 關(guān)閉數(shù)據(jù)庫(kù)連接
        db.close()
if __name__ == '__main__':
    main()

說(shuō)明

類(lèi)定義:

MySQLWrapper 類(lèi)封裝了與 MySQL 數(shù)據(jù)庫(kù)交互的所有方法。

__init__ 方法初始化數(shù)據(jù)庫(kù)連接參數(shù)。

connect 方法建立數(shù)據(jù)庫(kù)連接。

close 方法關(guān)閉數(shù)據(jù)庫(kù)連接。

execute_query 方法執(zhí)行 SQL 語(yǔ)句,并根據(jù)需要返回結(jié)果或提交更改。

query_data, insert_data, update_data, delete_data 方法分別封裝了查詢(xún)、插入、更新和刪除操作。

主函數(shù):

創(chuàng)建 MySQLWrapper 實(shí)例并連接到數(shù)據(jù)庫(kù)。

執(zhí)行查詢(xún)、插入、更新和刪除操作。

關(guān)閉數(shù)據(jù)庫(kù)連接。

運(yùn)行代碼

確保你已經(jīng)安裝了 mysql-connector-python 庫(kù):

pip install mysql-connector-python

然后運(yùn)行代碼:

python your_script_name.py

請(qǐng)將 your_script_name.py 替換為你的腳本文件名。

小結(jié)

通過(guò)上述步驟,我們封裝了 MySQL 數(shù)據(jù)庫(kù)的操作,包括連接數(shù)據(jù)庫(kù)、執(zhí)行 SQL 語(yǔ)句、查詢(xún)、插入、更新和刪除等常見(jiàn)功能。這樣的封裝方式不僅提高了代碼的可讀性和可維護(hù)性,還使得代碼更加簡(jiǎn)潔明了。你可以根據(jù)實(shí)際需求進(jìn)一步擴(kuò)展這些函數(shù)的功能,比如添加事務(wù)處理、錯(cuò)誤處理等。


責(zé)任編輯:華軒 來(lái)源: 測(cè)試開(kāi)發(fā)學(xué)習(xí)交流
相關(guān)推薦

2022-06-22 09:56:19

PythonMySQL數(shù)據(jù)庫(kù)

2017-12-21 15:03:31

PythonSQLiteMySQL

2021-08-02 09:01:29

PythonMySQL 數(shù)據(jù)庫(kù)

2019-05-20 16:30:36

PythonMySQL存儲(chǔ)

2010-06-01 15:54:46

MySQL-pytho

2020-07-02 16:20:36

MySQLCURD數(shù)據(jù)庫(kù)

2011-06-09 18:05:00

QT MySql

2018-04-26 16:35:44

PythonMySQL存儲(chǔ)

2022-08-16 10:20:06

PythonMySQL數(shù)據(jù)庫(kù)

2021-10-26 10:51:30

GoxormMySQL

2010-06-12 13:39:33

MySQL操作blob

2024-02-23 11:36:57

數(shù)據(jù)庫(kù)Python

2023-09-15 12:34:23

2016-10-13 19:16:28

Python編程語(yǔ)言mysql

2022-09-01 23:29:22

MySQLPython數(shù)據(jù)庫(kù)

2010-05-27 16:55:23

操作MySQL

2020-10-27 11:35:31

PythonRedis數(shù)據(jù)庫(kù)

2010-05-11 09:41:56

MySQL基本操作

2025-05-07 00:25:00

芯片焊料PC

2018-03-07 15:24:41

PythonMySQL
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)

主站蜘蛛池模板: 日韩av免费在线电影 | 日本五月婷婷 | 激情毛片 | 国产精品久久国产精品久久 | 男女视频在线观看网站 | 超碰天天| 亚州成人| 超碰在线观看97 | 99精品视频网 | www.毛片| 欧美精品一区二区三区蜜臀 | 91国在线视频 | 免费看91 | 色视频成人在线观看免 | 精品国产乱码久久久久久蜜退臀 | 久久精品99国产精品日本 | 好好的日在线视频 | 午夜免费网站 | xxxxx黄色片 欧美一区免费 | 日韩无| 欧美色999 | www.av在线| 国产成都精品91一区二区三 | 国产91亚洲精品一区二区三区 | 国产97碰免费视频 | 一区二区三区免费 | 天天综合网91 | 成人免费视频在线观看 | 国产成人精品一区二三区在线观看 | 日本特黄a级高清免费大片 国产精品久久性 | 国产一区二区三区四区三区四 | 91精品国产乱码麻豆白嫩 | 亚洲视频在线一区 | 日日干干 | 青青久草 | 在线播放日韩 | 成人精品一区二区 | 高清亚洲 | 欧美最猛性xxxxx亚洲精品 | 黄网站涩免费蜜桃网站 | 九九热这里只有精品在线观看 |