从 Jupyter 笔记本连接到 MySQL 数据库

2022-01-01 00:00:00 python jupyter-notebook mysql

我正在使用 Jupyter Notebooks 来学习 Python.我想连接到通过 MAMP 托管在本地的 MySQL 数据库.我将如何处理这个问题?

I am using Jupyter Notebooks to learn Python. I would like to connect to a MySQL db hosted locally hosted through MAMP. How would I approach this?

推荐答案

import os
import pymysql
import pandas as pd

host = os.getenv('MYSQL_HOST')
port = os.getenv('MYSQL_PORT')
user = os.getenv('MYSQL_USER')
password = os.getenv('MYSQL_PASSWORD')
database = os.getenv('MYSQL_DATABASE')

conn = pymysql.connect(
    host=host,
    port=int(3306),
    user="root",
    passwd=password,
    db="[YOUR_DB_NAME]",
    charset='utf8mb4')

df = pd.read_sql_query("SELECT * FROM YOUR_TABLE",
    conn)
df.tail(10)

相关文章