How to do some admin works with MariaDB and Python
The challenge for every administrator, especially database administrators, naturally lies in keeping track of what their own system is doing. I’m not a database administrator, meaning I don’t work full-time in this field 40 hours a week. But even for the hobbyist database administrator using MariaDB, some of this information is quite useful.
But I’ve been interested in databases for many years. I’m fascinated by data storage, because we encounter countless databases every day, even if we’re not aware of it.
The temptation for many people to call MariaDB, MySQL, or other database management systems overkill is surely on many people’s minds right now. I’ve often been asked why I have such a „huge“ behemoth on my computer instead of using a smaller database like SQLite3. I could also ask why some people drive SUVs when a Nissan Micra would do just as well.
Why do you need Microsoft Word, Excel, and Outlook at home? For home use, they’re completely overkill. The argument I’ve read countless times is that industry uses these programs, so it’s logical to have them at home, even just for practice. It’s probably the same argument as needing an SUV because you have to drive your relatives to the hospital every day ;-).
So, industry then? MariaDB and MySQL are also used in industry. But here it’s overkill. It’s strange how many people publicly construct their arguments.
Let’s have a look at how often SQLite3 appears in job postings. On Stepstone (Germany), this database can be found 15 times (MariaDB alone appears 85 times and MySQL 344 times).
I suspect they want to keep people down somehow. Nothing more. The people suggesting SQLite3 almost certainly also use MariaDB, MySQL, or even PostgreSQL at home.
What do I need for the script?
As usual, you’ll need Python, an installation of MariaDB, and the Python module mariadb. The other modules are already included in Python itself.
The command pip install mariadb installs the module for MariaDB.
For this you need a text editor and not a word processing program like Word, Writer or Google Doc.
Yes, the very simple text editor Notepad is better than Word. The script file must be saved with the .py extension.
The Script
import mariadb, sys, getpass, datetime, os, subprocess
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module="mariadb")
zeit_stempel = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
dateiname_log = f"{zeit_stempel}_mariadb_admin.log"
def servercheck():
result = subprocess.run(['systemctl', 'is-active', 'mariadb.service'],
capture_output=True, text=True)
return result.stdout.strip() == "active"
def ask_password():
while True:
wahl = input("\nPasswort (e)ingeben oder Programm (b)eenden? ").lower()
if wahl == 'b': sys.exit()
if wahl == 'e':
pw = getpass.getpass("Password: ")
if pw: return pw
print("Unvalid.")
def maria_db_connect(passwort):
try:
conn = mariadb.connect(
user="sven",
password=passwort,
host="localhost",
port=3306
)
cur = conn.cursor()
# 1. Database size
print("\n--- Checking of the database size ---")
cur.execute("""
SELECT table_schema, ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS Werte FROM information_schema.tables GROUP BY table_schema ORDER BY Werte DESC;
""")
databases = cur.fetchall()
for db in databases:
status_symbol = "✅"
if db[1] > 500:
status_symbol = "⚠️ Important: Big!"
print(f"{status_symbol} Database: {db[0]:<20} Size: {db[1]:>8} MB")
# 2. Server-Uptime
cur.execute("SHOW GLOBAL STATUS LIKE 'Uptime';")
uptime_seconds = int(cur.fetchone()[1])
uptime_minuten = uptime_seconds // 60
uptime_stunden = uptime_seconds // 3600
uptime_days = uptime_seconds // 86400
print(f"\n📊 Server-Uptime: {uptime_days} days, {uptime_stunden} hours, {uptime_minuten} minutes")
# 3. active process
print("\n🔍 active connection:")
cur.execute("SHOW PROCESSLIST;")
processes = cur.fetchall()
for p in processes:
print(f" ID: {p[0]} | User: {p[1]} | Status: {p[4]} | Info: {p[7]}")
# 4. Typeset
cur.execute("SHOW CHARACTER SET LIKE 'latin%';")
charsets = cur.fetchall()
# to log into one file
with open(dateiname_log, 'w') as log_file:
log_file.write(f"MARIADB ADMIN LOG - {zeit_stempel}\n")
log_file.write("="*40 + "\n")
log_file.write(f"Uptime: {uptime_days} Tage\n")
log_file.write(f"Prozesse: {len(processes)} aktiv\n\n")
log_file.write(f"Datenbank-Details:\n{str(databases)}\n\n")
log_file.write(f"Gefundene Charsets:\n{str(charsets)}\n")
print(f"\nReport was saved into'{dateiname_log}'.")
conn.close()
except mariadb.Error as e:
print(f"Connection error: {e}")
if __name__ == "__main__":
if servercheck():
print("MariaDB-Server is active.")
pw = ask_password()
maria_db_connect(pw)
else:
print("FEHLER: MariaDB-Server is not active.")
If you’re into running (jogging) and want to see how I handle real-world performance data, check out my E-Book. It’s available on Amazon and included in Kindle Unlimited.
Stop using „overkill“ tools only for work—start using them for your passions!.
