上一篇
如何实现使用远程连接类高效连接MySQL数据库?
- 行业动态
- 2024-10-06
- 1
import mysql.connector from mysql.connector import Error class RemoteMySQLConnection: def __init__(self, host, database, user, password, port=3306): """ 初始化连接参数。 :param host: 数据库的主机地址。 :param database: 要连接的数据库名。 :param user: 数据库的用户名。 :param password: 数据库的密码。 :param port: 数据库的端口号,默认为3306。 """ self.host = host self.database = database self.user = user self.password = password self.port = port self.connection = None def connect(self): """ 连接到MySQL数据库。 """ try: self.connection = mysql.connector.connect( host=self.host, database=self.database, user=self.user, password=self.password, port=self.port ) if self.connection.is_connected(): print("Successfully connected to the database") except Error as e: print("Error while connecting to MySQL", e) def close(self): """ 关闭数据库连接。 """ if self.connection.is_connected(): self.connection.close() print("MySQL connection is closed") def execute_query(self, query): """ 执行SQL查询。 :param query: 要执行的SQL查询字符串。 :return: 查询结果。 """ try: cursor = self.connection.cursor() cursor.execute(query) result = cursor.fetchall() return result except Error as e: print("Error while executing query", e) return None 使用示例 if __name__ == "__main__": # 替换以下变量为你的数据库连接信息 host = 'your_host' database = 'your_database' user = 'your_username' password = 'your_password' port = 3306 # 可选,默认为3306 # 创建连接对象 connection = RemoteMySQLConnection(host, database, user, password, port) # 连接到数据库 connection.connect() # 执行查询 query = "SELECT * FROM your_table" results = connection.execute_query(query) if results: for row in results: print(row) # 关闭连接 connection.close()
确保在运行此代码之前,你已经替换了your_host、your_database、your_username和your_password为实际的数据库连接信息,此代码示例提供了一个基础的连接、查询和断开连接的过程。
本站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本站,有问题联系侵删!
本文链接:http://www.xixizhuji.com/fuzhu/4810.html