JupySQL
Biblio
ipython-sql
JupySQL
PyMySQL: Pure Python MySQL/MariaDB Driver
MySQL Connector/Python
MariaDB Connector/Python
Demo: Sakila DB en MariaDB/MySQL con Jupyter
%load_ext sql
%config SqlMagic.autopandas=True
import pymysql
import pandas as pd
MariaDB JupySQL
%sql mysql+pymysql://jupyter:H4!b5at22@mariadb/sakila --alias mariadb
#%sql mariadb
%sql --connections
Active connections:
| current | url | alias |
| * | mysql+pymysql://jupyter:***@mariadb/sakila | mariadb |
| Name |
| actor |
| address |
| category |
| city |
| country |
| customer |
| film |
| film_actor |
| film_category |
| film_text |
| inventory |
| language |
| payment |
| rental |
| staff |
| store |
%%sql
SELECT * FROM actor
| actor_id | first_name | last_name | last_update |
| 0 | 1 | PENELOPE | GUINESS | 2006-02-15 04:34:33 |
| 1 | 2 | NICK | WAHLBERG | 2006-02-15 04:34:33 |
| 2 | 3 | ED | CHASE | 2006-02-15 04:34:33 |
| 3 | 4 | JENNIFER | DAVIS | 2006-02-15 04:34:33 |
| 4 | 5 | JOHNNY | LOLLOBRIGIDA | 2006-02-15 04:34:33 |
| ... | ... | ... | ... | ... |
| 198 | 199 | JULIA | FAWCETT | 2006-02-15 04:34:33 |
| 199 | 200 | THORA | TEMPLE | 2006-02-15 04:34:33 |
| 200 | 201 | ADW | ADE | 2006-02-15 01:31:33 |
| 201 | 202 | ADW | GII | 2006-02-15 02:31:33 |
| 202 | 203 | IBD | GCD | 2006-02-15 03:31:33 |
PyMySQL
conn = pymysql.connect(
host='mariadb',
port=3306,
user='jupyter',
password='H4!b5at22',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
# Cursor query
cur = conn.cursor()
cur.execute("select title, description, release_year from sakila.film limit 20")
output = cur.fetchall()
for i in output:
print(i)
# To close the connection
conn.close()
MariaDB Connector/Python
# Module Import
import mariadb
import sys
# Print List of Customers
def print_customers(cur):
"""Retrieves the list of actors from the database and prints to stdout"""
# Initialize Variables
customers = []
# Retrieve customers
cur.execute("SELECT first_name, last_name, email FROM sakila.customer LIMIT 20")
# Prepare customers
for (first_name, last_name, email) in cur:
customers.append(f"{first_name} {last_name}: <{email}>")
# List customers
print("\n".join(customers))
# Instantiate Connection
try:
conn = mariadb.connect(
host="mariadb",
port=3306,
user="jupyter",
password="H4!b5at22")
# Instantiate Cursor
cur = conn.cursor()
print_customers(cur)
# Close Connection
conn.close()
except mariadb.Error as e:
print(f"Error connecting to the database: {e}")
sys.exit(1)