python连接mysql模拟命令行输出

import pymysql
from configparser import ConfigParser
from prettytable import PrettyTable
import traceback

class MySQLManager:
    def __init__(self, config_file):
        self.config = ConfigParser()
        self.config.read(config_file, encoding="utf-8")
        self.host = self.config.get('mysql', 'host')
        self.port = int(self.config.get('mysql', 'port'))
        self.user = self.config.get('mysql', 'user')
        self.password = self.config.get('mysql', 'password')
        self.database = self.config.get('mysql', 'database')

    def connect(self):
        try:
            self.connection = pymysql.connect(
                host=self.host,
                port=self.port,
                user=self.user,
                password=self.password,
                database=self.database
            )
            self.cursor = self.connection.cursor()
            print("Connected to MySQL database")
        except pymysql.Error as e:
            print(f"Error connecting to MySQL database: {e}")

    def disconnect(self):
        try:
            self.cursor.close()
            self.connection.close()
            print("Disconnected from MySQL database")
        except pymysql.Error as e:
            print(f"Error disconnecting from MySQL database: {e}")

    def execute_query(self, query):
        try:
            self.cursor.execute(query)
            result = self.cursor.fetchall()
            return result
        except pymysql.Error as e:
            print(f"Error executing query: {e}")

    def execute_update(self, query):
        try:
            self.cursor.execute(query)
            self.connection.commit()
            print("Query executed successfully")
        except pymysql.Error as e:
            self.connection.rollback()
            print(f"Error executing query: {e}")

def pretty_output(list_head, row_datas):
    # 创建表格对象
    table = PrettyTable()
    # 添加字段名称
    table.field_names = list_head
    # 添加数据行
    for row in row_datas:
        table.add_row(row)
    # 设置对齐方式,默认为左对齐
    table.align = "l"
    # 输出表格
    print(table)


# 使用示例
if __name__ == "__main__":
    config_file = "config.ini"
    manager = MySQLManager(config_file)
    manager.connect()
    # 如果您想在 Python 打包成 exe 时出现错误时不自动关闭程序,可以在程序中添加以下代码:
    try:
        # 执行查询
        while True:
            query = input("mysql>")
            if query == "exit":
                break
            try:
                list_h = query.split()[1].split(",")
            except IndexError:
                print("输入格式错误")
                continue
            results = manager.execute_query(query)
            list_t = []
            for result in results:
                list_t.append(list(result))
            pretty_output(list_h, list_t)
    except Exception as e:
        # 这将捕获所有异常,并使用 traceback 打印出错误信息。然后程序将等待用户按下任意键,以便您可以查看错误信息并解决问题。
        traceback.print_exc()
        input("Press any key to exit...")

    # 执行更新
    # update_query = "UPDATE table_name SET column_name = 'new_value' WHERE condition"
    # manager.execute_update(update_query)
    manager.disconnect()

python同级目录下创建config.ini替换数据库连接信息

[mysql]
host = xxx.xx.3xxx.8x4
port = 3306
user = root
password = xxxx
database = xxxxxxx

你可能感兴趣的:(python,mysql,adb)