阅读量:0
import mysql.connector from mysql.connector import Error def create_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("Connection to MySQL DB successful") except Error as e: print(f"The error '{e}' occurred") return connection def switch_database(connection, new_db_name): try: # Switch to the new database cursor = connection.cursor() cursor.execute(f"USE {new_db_name}") print(f"Switched to database: {new_db_name}") except Error as e: print(f"The error '{e}' occurred while switching database") def main(): # Database configuration host_name = 'localhost' user_name = 'your_username' user_password = 'your_password' db_name = 'original_db_name' new_db_name = 'new_db_name' # Create connection to the original database connection = create_connection(host_name, user_name, user_password, db_name) # Switch to the new database if connection: switch_database(connection, new_db_name) if __name__ == "__main__": main()
代码块包含了以下步骤:
1、create_connection
函数用于创建到MySQL数据库的连接。
2、switch_database
函数用于切换当前连接到的数据库。
3、main
函数是程序的入口点,它配置数据库连接信息,创建连接,并切换到新的数据库。
请根据您的实际数据库配置替换your_username
、your_password
、original_db_name
和new_db_name
,此代码块假设您已经安装了MySQL Connector/Python,如果没有安装,您需要先安装它,因为这是连接MySQL数据库所需的Python库。