阅读量:0
import mysql.connector from mysql.connector import Error def create_database_connection(host_name, user_name, user_password, db_name): connection = None try: connection = mysql.connector.connect( host=host_name, user=user_name, passwd=user_password, database=db_name ) print("MySQL Database connection successful") except Error as e: print(f"The error '{e}' occurred") return connection 使用示例 if __name__ == "__main__": # 数据库连接参数 host_name = 'localhost' user_name = 'your_username' user_password = 'your_password' db_name = 'your_database_name' # 调用函数创建数据库连接 connection = create_database_connection(host_name, user_name, user_password, db_name) # 关闭数据库连接 if connection.is_connected(): connection.close() print("MySQL connection is closed")
这段代码首先导入了mysql.connector
模块,该模块是MySQL官方提供的Python连接器。create_database_connection
函数用于建立与MySQL数据库的连接,接收主机名、用户名、密码和数据库名作为参数,如果连接成功,它会打印一条消息;如果发生错误,它会打印错误信息,示例中提供了如何使用这个函数来连接到数据库,并在连接完成后关闭连接。