从Jupyter Notebook连接到MySQL数据库

时间:2018-06-21 16:14:18

标签: python mysql mamp

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

4 个答案:

答案 0 :(得分:6)

假设您已安装MySQL(使用HomeBrew的macOS使用说明here),您需要:

  • 安装pip3 install ipython-sql
  • pip3 install mysqlclient

现在您应该能够运行这些单元并获得打印精美的HTML输出:

# %%
%load_ext sql

# %%
%sql mysql+mysqldb://<user>:<password>@localhost/<dataBase>

# %%
%%sql

SELECT *
FROM <table>;

答案 1 :(得分:5)

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)

答案 2 :(得分:3)

import pymysql

import pandas as a

conn=pymysql.connect(host='localhost',port=int(3306),user='root',passwd='YOUR_PASSWORD',db='YOUR_DATABASENAME')

df=a.read_sql_query("SELECT * FROM 'YOUR_TABLENAME' ",conn)

print(df)

答案 3 :(得分:1)

是的,可以。您可以使用MySQL Connector库。只需使用pip安装它,然后就可以使用它与数据库进行交互。请参见下面的示例代码:

import mysql.connector

db = mysql.connector.connect(
   host="localhost",
   user="mamp",
   passwd=""
)

print(db)