Connect to MySQL db from Jupyter notebook

时光毁灭记忆、已成空白 提交于 2020-05-08 04:07:30

问题


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?


回答1:


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:


Yes, you can. You can use the MySQL Connector library. Simply install it using pip, and then you can use it to interact with your database. See the sample code below:

import mysql.connector

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

print(db)



回答3:


Assuming you have MySQL installed (instructions here for macOS using HomeBrew), you need to:

  • Install pip3 install ipython-sql
  • pip3 install mysqlclient

now you should be able to run these cells and get pretty-printed HTML output:

# %%
%load_ext sql

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

# %%
%%sql

SELECT *
FROM <table>;



回答4:


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)


来源:https://stackoverflow.com/questions/50973191/connect-to-mysql-db-from-jupyter-notebook

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!