How to connect MySQL DB in Python?
0

How to connect MySQL DB in Python?

This recipe helps you connect MySQL DB in Python
In [3]:
## How to connect MySQL DB in Python
def Snippet_166():
    print()
    print(format('How to connect MySQL DB in Python','*^82'))
    import warnings
    warnings.filterwarnings("ignore")
    # load libraries
    import sqlalchemy as sa
    import pandas as pd

    dataset = pd.read_csv("iris.data.csv")
    engine_str = (
      'mysql+pymysql://{user}:{password}@{server}/{database}'.format(
       user      =  'root',
       password  =  'root888',
       server    =  'localhost',
       database  =  'datasciencerecipes'))
    engine = sa.create_engine(engine_str)
    conn = engine.connect()

    # check whether connection is Successful or not
    if (conn):
        print("MySQL Connection is Successful ... ... ...")
    else:
        print("MySQL Connection is not Successful ... ... ...")

    dataset.to_sql(name='irisdata', con=engine,
                   schema='datasciencerecipes',
                   if_exists = 'replace', chunksize = 1000,
                   index=False)
    conn.close()
Snippet_166()
************************How to connect MySQL DB in Python*************************
MySQL Connection is Successful ... ... ...