Python with a MariaDB client
475
This Docker image provides a Python interpreter with the MariaDB Connector/Python pre-installed, running on Alpine Linux. It's designed to simplify connecting to MariaDB databases from within Docker containers.
This walkthrough shows how to connect to a MariaDB server using this image. It assumes you have Docker installed. It also assumes you have a MariaDB server running.
If you don't already have a MariaDB server running, use the agentlans/mariadb-sample image.
# Create a new network (if not already existing)
docker network create some-network
# Start the MariaDB server with sample data
docker run --detach \
--network some-network \
--name some-mariadb \
--env MARIADB_USER=example-user \
--env MARIADB_PASSWORD=my_cool_secret \
--env MARIADB_ROOT_PASSWORD=my-secret-pw \
--env MARIADB_DATABASE=employees \
agentlans/mariadb-sample
# Check that the server is running
docker ps -a | grep some-mariadb
Start the client container, connecting it to the same Docker network as the MariaDB server. This ensures the client can resolve the MariaDB server's hostname.
docker run -it --rm --network some-network agentlans/python-mariadb
Once inside the container, start the Python interpreter:
python3
Then, use the following Python code to connect to the MariaDB server and execute a sample query:
import mariadb
import sys
# Connect to MariaDB Platform
try:
conn = mariadb.connect(
user="example-user",
password="my_cool_secret",
host="some-mariadb",
port=3306,
database="employees"
)
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)
# Get Cursor
cur = conn.cursor()
# List 10 employees whose first name starts with the letter A
cur.execute(
"SELECT first_name,last_name FROM employees WHERE first_name LIKE ? LIMIT 10",
("A%",))
# Print Result-set
for (first_name, last_name) in cur:
print(f"First Name: {first_name}, Last Name: {last_name}")
# Disconnect
conn.close()
This code connects to the MariaDB server running on the some-mariadb hostname (which resolves within the Docker network), retrieves the first name and last name of 10 employees whose first name starts with "A", and prints the results. Remember to adjust the connection parameters to match your MariaDB server's configuration.
For detailed information on connecting Python programs to MariaDB, refer to the official MariaDB documentation:
Content type
Image
Digest
sha256:0717d4972…
Size
118.4 MB
Last updated
over 1 year ago
docker pull agentlans/python-mariadb