DEV Community

Dmitry Romanoff
Dmitry Romanoff

Posted on

1

Python. Exploring MySQL Table Sizes.

This Python code is useful for monitoring the sizes of tables in a MySQL database. It connects to the database and prints out the tables and their sizes, sorting the data in descending order by table size.

import mysql.connector

# MySQL database connection parameters
config = {
  'user': 'root',
  'password': '123456',
  'host': '127.0.0.1',
  'database': 'my_database',
  'port' : 3306,
  'raise_on_warnings': True
}

# Connecting to the MySQL database
try:
    cnx = mysql.connector.connect(**config)
    cursor = cnx.cursor()

    # SQL query to retrieve table sizes
    query = ("SELECT table_name, ROUND((data_length + index_length) / 1024 / 1024, 2) AS 'size_mb' "
             "FROM information_schema.tables "
             "WHERE table_schema = %(database)s "
             "ORDER BY size_mb DESC")

    cursor.execute(query, {'database': config['database']})

    # Printing the results
    print("Table Name\tSize (MB)")
    print("-------------------------")
    for (table_name, size_mb) in cursor:
        print(f"{table_name}\t\t{size_mb}")

    cursor.close()
    cnx.close()

except mysql.connector.Error as err:
    print(f"Error: {err}")

Enter fullscreen mode Exit fullscreen mode

Example of how it works:

dmi@dmi-laptop:~/my_python$ python3 mysql_db_tables_sizes.py 
Table Name  Size (MB)
-------------------------
three       24.56
one     13.52
two     1.52
dmi@dmi-laptop:~/my_python$ 
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs