Create Database in MariaDB using PyMySQL in Python

Create Database in MariaDB using PyMySQL in Python

To create a database in MariaDB using PyMySQL in Python, you need to follow several steps:

  1. Install PyMySQL: If you don't have PyMySQL installed, you can install it via pip:

    pip install pymysql 
  2. Import PyMySQL: In your Python script, import PyMySQL.

  3. Establish a Connection: Connect to your MariaDB server. You usually need the host, user, and password.

  4. Create a Cursor Object: Cursor objects allow Python code to execute MariaDB command in a database session.

  5. Execute a Query to Create Database: Use the cursor to execute an SQL command that creates a database.

  6. Close the Connection: It's a good practice to close the connection when done.

Here's an example script that demonstrates these steps:

import pymysql # Database configuration host_name = "localhost" user_name = "your_username" user_password = "your_password" # Establish a database connection connection = pymysql.connect(host=host_name, user=user_name, password=user_password) cursor = connection.cursor() # SQL query to create a database create_database_query = "CREATE DATABASE IF NOT EXISTS example_db" # Execute the SQL query try: cursor.execute(create_database_query) print("Database created successfully") except Exception as e: print(f"An error occurred: {e}") # Close the connection finally: connection.close() 

In this script, replace "your_username" and "your_password" with your actual MariaDB username and password. The database "example_db" is created if it doesn't already exist.

Important Considerations

  • Database User Permissions: The user should have the necessary permissions to create databases.

  • Exception Handling: It's important to handle exceptions that may occur during database operations. This example uses a basic try-except block.

  • Database Connection: Ensure your database server is running and accessible from where your script is running.

  • Security: Be cautious with handling login credentials in your scripts, especially if the script is shared or accessible publicly.

By following these steps, you should be able to create a new database in MariaDB using PyMySQL in Python.


More Tags

custom-pages tabpage apex userscripts rhel7 query-performance safari browser-testing react-css-modules disabled-input

More Programming Guides

Other Guides

More Programming Examples