Run MariaDB and Python on the same VPS, create a database account limited to the application, and connect with MariaDB Connector/Python. Use a Unix socket or loopback for local traffic, parameterized statements for every value, explicit commits and rollbacks, and scheduled off-server backups. Open TCP port 3306 only when another machine genuinely needs database access.
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
What you need before writing Python code
This setup has four independent parts: a MariaDB server, an application database and account, the Python connector, and a safe network path between the process and server. Treat each as a separate configuration task; a successful connection does not prove that permissions, backups, or remote-access controls are correct.
As an Amazon Associate I earn from qualifying purchases.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →- A Linux VPS with administrative access and a supported MariaDB package for its distribution.
- Python 3 and a virtual environment for the application.
- A MariaDB database and a non-root account used only by the application.
- A plan for where encrypted backups will be stored away from the VPS.
MariaDB Connector/Python is the official client for Python programs talking to MariaDB and MySQL. It follows Python DB API 2.0 (PEP 249), so the usual connection, cursor, parameter, transaction, and fetch patterns apply. Connector releases, supported Python versions, package names, and parameter styles can change; check the documentation for the major version you install before putting the code into production.
Install and secure MariaDB on the VPS
Use the distribution-supported repository
Install MariaDB Server from the repository and package instructions supported by your Linux distribution. A Debian- or Ubuntu-based system commonly uses:
#1 Best Overall
- BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
- EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
- COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
- LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
- WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.
sudo apt update
sudo apt install mariadb-server mariadb-client
sudo systemctl enable --now mariadb
Other distributions use different package names and service-management commands. Confirm that the service is running with the system’s service manager and check the installed server version with:
mariadb --version
sudo systemctl status mariadb
Run the vendor’s hardening procedure where it is provided. Remove anonymous accounts and test databases if they are present, set an administrative authentication method you understand, and do not use the administrative account from application code.
Create a database and a least-privilege account
Log in locally as an administrator and create a database with an explicit character set. The following example grants only the operations used by a small notes application:
sudo mariadb
CREATE DATABASE app_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'replace-with-a-long-secret';
GRANT SELECT, INSERT, UPDATE, DELETE ON app_db.* TO 'app_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
Generate the password outside shell history and store it in an environment variable or a secret store. Do not put it in source control, a command recorded in a shared shell history, or a world-readable configuration file. If the process connects through a Unix socket, the 'localhost' host qualifier is normally appropriate. A TCP connection from another machine needs a different, tightly scoped host qualifier, described below.
Grant additional privileges only when a demonstrated migration or operational task needs them. For example, schema changes can be run by a separate deployment account instead of giving the runtime account broad administrative rights.
Install MariaDB Connector/Python in a virtual environment
Keep the connector isolated from the system Python installation and pin a release that your application has tested:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Rank #2
- WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
- AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
- PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
- ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
- COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed
python3 -m venv .venv
. .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install mariadb
python -m pip show mariadb
The package is named mariadb, while the module imported by programs is also named mariadb. Record the resulting version in your deployment lock file. Before an upgrade, verify its supported Python versions, connection options, and placeholder behavior; do not assume that defaults from an older connector major version remain unchanged.
Choose a connection path: socket, loopback, or remote TCP
For a Python process running on the same VPS, keep traffic local. A Unix-domain socket avoids TCP exposure and normally has less configuration. Loopback TCP (127.0.0.1) is also local and can be useful when software expects a TCP endpoint. The connector can autodetect a Linux socket in common configurations, but socket locations vary by distribution, so specify the path when autodetection fails.
| Path | When to use it | What must be configured | Main risk |
|---|---|---|---|
| Unix socket | Application and MariaDB share the VPS | Correct socket path and filesystem permissions | A wrong path produces a local connection error |
| Loopback TCP | Both processes are local but a TCP endpoint is required | host='127.0.0.1' and the local port |
It is still TCP, so confirm MariaDB is not bound to public interfaces |
| Private-network TCP | A separate trusted application host must connect | Required bind address, host-scoped account, firewall rule, and TLS where appropriate | Misconfiguration can expose port 3306 or over-grant an account |
| Public-internet TCP | Only as a last resort with a carefully designed security plan | Restricted source addresses, encryption, monitoring, and hardened credentials | Scanning, credential attacks, and accidental broad access |
MariaDB’s skip-networking option disables TCP/IP listening, while bind-address determines which local address accepts TCP connections. A firewall can block incoming connections even when MariaDB is listening; listening and reachability are separate controls.
Create a reusable Python connection
Keyword arguments make the important settings visible. This example reads the secret from the process environment and uses a local connection:
import os
import mariadb
def open_connection():
return mariadb.connect(
host=os.getenv('DB_HOST', 'localhost'),
port=int(os.getenv('DB_PORT', '3306')),
user=os.environ['DB_USER'],
password=os.environ['DB_PASSWORD'],
database=os.environ['DB_NAME'],
# unix_socket='/run/mysqld/mysqld.sock', # set when required
connect_timeout=5,
)
Set DB_USER, DB_PASSWORD, and DB_NAME in the service manager or deployment environment. The default TCP port is 3306. If you use a socket, provide the actual path instead of guessing it; common paths differ between distributions and package layouts. Connector/Python also documents URI connection forms and optional binary or prepared-protocol behavior. Use the form supported by your installed connector version, and never place a secret in a URI that may be logged.
Design a table before inserting rows
Use explicit data types, a primary key, and indexes that match real lookup queries. For a notes table:
Rank #3
- Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
- Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
- Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
- ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
- Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
CREATE TABLE notes (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
body TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
INDEX notes_created_at_idx (created_at)
) ENGINE=InnoDB;
InnoDB is the usual choice for transactional application data. Add an index only for a query pattern you actually use; every additional index consumes storage and makes writes do more work. Keep schema creation and migrations in a controlled deployment process rather than granting the runtime account unrestricted DDL privileges.
Insert, retrieve, update, and delete safely
Use placeholders for values and pass the values separately. Never build SQL by concatenating a username, note body, identifier, or other input into the statement. The following complete example uses the DB API cursor and transaction methods:
import mariadb
def add_and_read_note(body, note_id):
conn = None
cur = None
try:
conn = open_connection()
cur = conn.cursor()
cur.execute(
'INSERT INTO notes (body) VALUES (?)',
(body,)
)
conn.commit()
cur.execute(
'SELECT id, body, created_at, updated_at '
'FROM notes WHERE id = ?',
(note_id,)
)
return cur.fetchone()
except mariadb.Error:
if conn is not None:
conn.rollback()
raise
finally:
if cur is not None:
cur.close()
if conn is not None:
conn.close()
The ? placeholder is representative of the connector’s qmark style. Connector/Python documents supported parameter styles; check the installed major version rather than changing placeholders by guesswork. A parameter tuple needs a trailing comma for a single value, as in (note_id,).
Use the same pattern for each write operation
def update_note(note_id, body):
conn = None
try:
conn = open_connection()
cur = conn.cursor()
cur.execute(
'UPDATE notes SET body = ? WHERE id = ?',
(body, note_id)
)
conn.commit()
return cur.rowcount
except mariadb.Error:
if conn is not None:
conn.rollback()
raise
finally:
if conn is not None:
conn.close()
def delete_note(note_id):
conn = None
try:
conn = open_connection()
cur = conn.cursor()
cur.execute('DELETE FROM notes WHERE id = ?', (note_id,))
conn.commit()
return cur.rowcount
except mariadb.Error:
if conn is not None:
conn.rollback()
raise
finally:
if conn is not None:
conn.close()
Commit only after the statements that form one logical change have succeeded. If any statement fails, roll back before propagating the exception. Do not enable autocommit merely to avoid thinking about transaction boundaries: it can leave a multi-step operation partially applied.
Retrieve more than one row without wasting memory
A cursor can return one row with fetchone(), all remaining rows with fetchall(), or batches with fetchmany(). For a small result set:
def recent_notes(limit=50):
conn = open_connection()
cur = conn.cursor()
try:
cur.execute(
'SELECT id, body, created_at '
'FROM notes ORDER BY created_at DESC, id DESC '
'LIMIT ?',
(limit,)
)
return cur.fetchall()
finally:
cur.close()
conn.close()
Validate limits in application code and cap them to a sensible maximum. For a large export, iterate over the cursor or use batches rather than loading every row into memory. Offset pagination is simple but becomes less efficient as the offset grows. A keyset query based on the last created_at and id is usually a better design for a continuously growing table; index the columns used by that ordering and test the query with your data.
Free tools Windows power users keep installed
One-click scans. No signup required.
Rank #4
- Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
- Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
- 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
- Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
- USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC
Manage connections and concurrency deliberately
A short-lived command can open one connection, complete its work, and close it in a finally block. A long-running web worker should not leak connections on exceptions. Keep cursor lifetimes shorter than connection lifetimes, and return connections to the application’s pool if you introduce pooling.
Start with a single connection per unit of work and measure before adding a pool. A pool reduces connection setup overhead under concurrent load but introduces limits, stale-connection handling, shutdown behavior, and transaction-reset requirements. The correct pool size depends on the application’s concurrency and MariaDB’s configured resources; there is no universal VPS number. Never share one cursor simultaneously across threads, and ensure a connection is not reused while an unfinished transaction belongs to another request.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Allow remote access only when the topology requires it
Configure the server interface
For a second machine, edit the MariaDB server configuration to listen on the required private address with bind-address. Ensure skip-networking is not disabling TCP if TCP is required, then restart MariaDB and verify the listening address locally. Bind to a private interface rather than every interface whenever possible.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesGrant access to the expected source host
Use a host-qualified account that matches the application’s private address or tightly bounded subnet:
CREATE USER 'app_remote'@'10.20.30.15' IDENTIFIED BY 'another-long-secret';
GRANT SELECT, INSERT, UPDATE, DELETE ON app_db.*
TO 'app_remote'@'10.20.30.15';
FLUSH PRIVILEGES;
Do not replace the source address with a broad wildcard unless you have a specific, documented reason and compensating controls. The account’s host qualifier is part of MariaDB authentication; it is not a substitute for a firewall.
Restrict the firewall and encrypt the connection
Permit inbound 3306 only from the application’s private address in the VPS firewall. For example, an uncomplicated-firewall setup might use:
Best Value
- Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
- Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
- Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
- Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
- Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
sudo ufw allow from 10.20.30.15 to any port 3306 proto tcp
sudo ufw status verbose
Use the firewall tool and syntax supported by your distribution. Prefer a private network or an SSH tunnel over exposing MariaDB publicly. If TCP crosses a network you do not fully trust, configure TLS on the server and the connector according to their installed versions, verify certificates, and do not silently disable certificate checking. Never expose an administrative or root account to the internet.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallBack up MariaDB and prove that recovery works
Logical backup with mariadb-dump
mariadb-dump exports SQL statements that can recreate tables and data. A typical InnoDB dump is:
mariadb-dump
--user=backup_user
--password
--single-transaction
--routines --events --triggers
app_db > app_db-$(date +%F).sql
--single-transaction provides a consistent snapshot for transactional tables without taking the same kind of long table lock as a traditional dump. It does not make nontransactional tables magically consistent, so verify engine choices and workload behavior. Protect the dump file because it contains the data in readable form, compress it only after considering how it will be encrypted, and copy it to storage that is separate from the VPS.
Restore into a prepared database with:
mariadb --user=restore_user --password app_db < app_db-2026-10-15.sql
Use the actual dump filename and restore account. Test restores on an isolated host, check row counts and application behavior, and document the commands so an outage does not become an improvisation exercise.
Physical backup with mariadb-backup
mariadb-backup creates physical backups of the server’s data files and is designed for engines including InnoDB. A simplified workflow is:
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →mariadb-backup --backup
--target-dir=/srv/mariadb-backups/2026-10-15
--user=backup_user --password
mariadb-backup --prepare
--target-dir=/srv/mariadb-backups/2026-10-15
Restoration normally requires stopping MariaDB, ensuring the destination data directory is empty and owned correctly, and using the utility’s documented copy-back procedure. Physical backups are tied more closely to server versions, configuration, filesystem space, and InnoDB state than SQL dumps. Follow the current utility documentation for the exact restore sequence rather than treating the two tools as interchangeable.
Define retention and recovery targets
Choose how many daily, weekly, and monthly copies to retain based on the data’s value and change rate. Decide how much data loss (recovery-point objective) and downtime (recovery-time objective) the application can tolerate. Schedule the job, alert on failure, encrypt transfers and stored copies, restrict backup credentials, and keep at least one copy unavailable to a compromised VPS. The utilities provide mechanisms; retention, storage location, and recovery objectives are application decisions.
Troubleshoot the failures you are most likely to see
| Symptom | Checks | Typical correction |
|---|---|---|
| Connection refused | Check service status, listening address, port, and firewall; confirm that TCP is actually enabled. | Start MariaDB, correct bind-address, or allow the source address only if remote access is required. |
| Can’t connect through a socket | Find the server’s configured socket path and compare it with the connector argument. | Set unix_socket explicitly or use loopback TCP. |
| Access denied | Verify username, secret, database name, and the account’s host qualifier. | Use the intended application account and grant only the required privileges for that host. |
| SQL syntax or parameter error | Check the connector major version and its documented parameter style. | Keep values in the parameter tuple and use the placeholder syntax supported by that release. |
| Rows disappear after a crash | Check whether the code committed the transaction and whether an exception triggered rollback. | Define the transaction boundary and call commit() only after all related writes succeed. |
| Backup restores but the application fails | Check schema version, routines, triggers, character set, users, and application configuration. | Restore into a test environment and run the application’s migrations and smoke tests before relying on the backup. |
Production checklist
- MariaDB is installed from a supported repository and its service starts automatically.
- The application uses a dedicated account, never the root account.
- Privileges cover only the required database and operations.
- Local processes use a Unix socket or loopback unless a real network hop is needed.
- Every external value is passed as a parameter, not concatenated into SQL.
- Writes have explicit commit and rollback paths, with cursors and connections closed reliably.
- Remote TCP, if required, is bound to the needed interface, restricted by host-scoped grants and firewall rules, and protected with TLS where appropriate.
- Logical or physical backups run on a schedule, are copied off the VPS, and are protected from unauthorized access.
- A documented restore test has succeeded, including application-level checks.
- Connector and server versions are recorded, and upgrades are tested before deployment.
The dependable default is straightforward: keep MariaDB private, give Python the smallest useful account, parameterize every statement, make transaction boundaries explicit, and treat a backup as real only after a restore has been rehearsed.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Recommended Free Tools




