Monday, April 21, 2025

Create MySQL Databases from .TXT File - Python

import mysql.connector, time

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

print(db_handle)

kursor = db_handle.cursor()

names = []

file = open("database_names.txt", 'r')

for x in file.readlines():
    names.append(x)

for y in names:
    kursor.execute("CREATE DATABASE " + y)
    time.sleep(2)

file.close()

This code imports two modules, "mysql.connector" and "time".

The "mysql.connector" module is used to connect to a MySQL database server, and execute queries on it. It is a Python library that provides a standardized way to interact with the MySQL database.

The "time" module is used to introduce a delay in the execution of the code. In this particular code, it is used to introduce a delay of 2 seconds after creating each database.

The code establishes a connection to the MySQL database server running on "localhost" with the username "root" and password "12345". It then creates a cursor object to execute queries on the database.

It reads the names of databases from the file "database_names.txt" and stores them in a list called "names".

Then it uses a loop to execute a "CREATE DATABASE" query for each name in the "names" list, using the cursor object. The time.sleep(2) function is used to introduce a delay of 2 seconds between each database creation.

Finally, it closes the file. 

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| 192_168_0_103      |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test_1             |
| test_2             |
| test_3             |
+--------------------+
8 rows in set (0.00 sec)

mysql>

This is the output of the MySQL command "show databases". It displays a list of all the databases that are currently present on the MySQL server.

In this case, there are 8 databases in the list.

The "information_schema", "mysql", "performance_schema", and "sys" databases are default databases that are created when MySQL is installed.

Last 3 databases ("test_1", "test_2", and "test_3") are created by us, based on their names from .txt file.

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 .  ...