In Python, With the help of connect() and execute() methods, we can establish a connection, create a Database in MySQL and manipulate the data using Python programming language. we need to install the "mysql-connector-python" module.
First, we need to install "pip" if haven't installed it already.
Here's how we can configure the Create Mysql database in Python using the "mysql-connector-python" library:
After installing the package, we can use it to establish a connection to our MySQL database and perform operations.
pip install mysql-connector-python
Import `mysql.connector` library and create a configuration object with keys such as user, password, host, and database.
# import mysql connector library import mysql.connector # Configuration parameters config = { 'user': 'your_username', 'password': 'your_password', 'host': 'localhost', # or your host address 'database': 'your_database_name' }
Try to Establish a connection with the MySQL database by passing the configuration object to the `connect()` method. Once the connection is established successfully then, create a Database using the `execute()` method.
Catch the error if it arises while connecting with the database in `except` statement.
try: # Establish a connection to the MySQL server connection = mysql.connector.connect(**config) # Checking connection with database established successfully if connection.is_connected(): # Create a new database cursor = connection.cursor() database_name = 'new_database' create_database_query = f"CREATE DATABASE {database_name}" # execute above query with `execute` method cursor.execute(create_database_query) # print database with message if database created successfully print(f"Database '{database_name}' created successfully") except mysql.connector.Error as error: print("Error occurred while connecting to MySQL:", error)
# import mysql connector library import mysql.connector # Configuration parameters config = { 'user': 'your_username', 'password': 'your_password', 'host': 'localhost', # or your host address 'database': 'your_database_name' } try: # Establish a connection to the MySQL server connection = mysql.connector.connect(**config) if connection.is_connected(): # Create a new database cursor = connection.cursor() database_name = 'new_database' create_database_query = f"CREATE DATABASE {database_name}" cursor.execute(create_database_query) print(f"Database '{database_name}' created successfully") except mysql.connector.Error as error: print("Error occurred while connecting to MySQL:", error) finally: if 'connection' in locals() and connection.is_connected(): cursor.close() connection.close() print("MySQL connection is closed")
Make sure to replace 'your_username' and 'your_password' with your actual MySQL credentials.
This script connects to the MySQL server, creates a new database named 'new_database', and prints a success message if the operation is successful.
Remember to handle exceptions and close the connection properly.