Monday, April 21, 2025

Create Multiple MySQL Databases Automatically - Python

import mysql.connector, time

db_handle = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '12345'
)

print(db_handle)

kursor = db_handle.cursor()

bases = ["slavoj", "zizek", "jordan", "peterson"]

for x in bases:
    kursor.execute("CREATE DATABASE " + x)
    time.sleep(2)

This script creates multiple databases in a MySQL server using Python with the mysql-connector package and the time module.

First, it establishes a connection to the MySQL server with the specified host, user, and password using the mysql.connector.connect() function, and then prints the handle to the database.

Then, it creates a cursor object using the cursor() method of the database handle, which is used to execute SQL statements.

Next, it defines a list of database names to be created, bases.

The script then loops over the list of database names, and for each name, it executes a SQL CREATE DATABASE statement with the corresponding name using the execute() method of the cursor object. It also includes a 2-second delay between each database creation using the time.sleep() function.

Our script will create four databases with the names "slavoj", "zizek", "jordan", and "peterson".

Result: 

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| 192_168_0_103      |
| information_schema |
| jordan             |
| mysql              |
| performance_schema |
| peterson           |
| slavoj             |
| sys                |
| test_dba           |
| zizek              |
+--------------------+
10 rows in set (0.00 sec)

mysql>

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...