在 Python 中安装 mysql.connector 库,您可以使用 pip 包管理器进行安装。如果您的系统上已安装了 pip,请在命令行/终端中执行以下命令:

    1. pip3 install mysql-connector-python -i https://mirrors.aliyun.com/pypi/simple

    安装完成后,您可以在 Python 代码中导入 mysql.connector 模块并使用它来连接到 MySQL 数据库。
    例如:

    1. import sys
    2. import mysql.connector
    3. # pip3 install mysql-connector-python -i https://mirrors.aliyun.com/pypi/simple
    4. class MySQLConnector:
    5. def __init__(self, user, password, host, port, database):
    6. self.user = user
    7. self.password = password
    8. self.host = host
    9. self.database = database
    10. self.port = port
    11. self.cnx = None
    12. def connect(self):
    13. try:
    14. self.cnx = mysql.connector.connect(
    15. user=self.user, password=self.password, host=self.host, database=self.database, port=self.port)
    16. print("Successfully connected to MySQL database!")
    17. return True
    18. except mysql.connector.Error as err:
    19. print("Failed to connect to MySQL database: {}".format(err))
    20. return False
    21. def close(self):
    22. if self.cnx:
    23. self.cnx.close()
    24. print("Connection to MySQL database is closed.")
    25. if __name__ == '__main__':
    26. # 禁止生成 __pycache__
    27. sys.dont_write_bytecode = True
    28. connector = MySQLConnector(
    29. user='root', password='your_password', host='your_host', port=3306, database='your_database')
    30. if connector.connect():
    31. connector.close()