7

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?

Slava Rozhnev
  • 8,085
  • 6
  • 21
  • 35
coderatlarge
  • 497
  • 3
  • 7
  • 19
  • 1
    Possible duplicate of [How do I connect to a MySQL Database in Python?](https://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python) – Rushil Srivastava Jun 21 '18 at 16:30

4 Answers4

12
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)
tammuz
  • 343
  • 3
  • 12
7

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>;
Foad S. Farimani
  • 10,712
  • 13
  • 53
  • 162
7
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)
StupidWolf
  • 41,371
  • 17
  • 31
  • 62
VADHAN
  • 201
  • 3
  • 2
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)
  • What about using Scala in Notebook? Thanks. I am having trouble with Scala: https://stackoverflow.com/questions/55154372/com-mysql-jdbc-driver-not-found-in-spark2-scala, thank you very much. – mdivk Mar 15 '19 at 01:30