Extracted Pages From Unit No. 1 Data Handling Python Pandas Part 2
This document provides code samples for importing and exporting data between a Pandas dataframe and a MySQL database. It shows how to import data from a MySQL table into a dataframe using mysql.connector and SELECT. It also demonstrates exporting data from a dataframe to a MySQL table using DataFrame.to_sql() and SQLAlchemy to connect to the database.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
97 views2 pages
Extracted Pages From Unit No. 1 Data Handling Python Pandas Part 2
This document provides code samples for importing and exporting data between a Pandas dataframe and a MySQL database. It shows how to import data from a MySQL table into a dataframe using mysql.connector and SELECT. It also demonstrates exporting data from a dataframe to a MySQL table using DataFrame.to_sql() and SQLAlchemy to connect to the database.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2
Importing data from a
MySQL database into a
Pandas data frame import mysql.connector as sql import pandas as pd db_connection = sql.connect(host='localhost', database='bank', user='root', password='root') db_cursor = db_connection.cursor() db_cursor.execute('SELECT * FROM bmaster') table_rows = db_cursor.fetchall() df = pd.DataFrame(table_rows) print(df)
OUTPUT Will be as data available in table bmaster
Note :- for mysql.connector library use pip install mysql_connector command in
command prompt. Pass proper host name,database name,user name and password in connect method. Visit : python.mykvs.in for regular updates Exporting data to a MySQL database from a Pandas data frame import pandas as pd from sqlalchemy import create_engine engine = create_engine('mysql+mysqlconnector://root:root@localhost/bank') lst = ['vishal', 'ram'] lst2 = [11, 22] # Calling DataFrame constructor after zipping # both lists, with columns specified df = pd.DataFrame(list(zip(lst, lst2)), columns =['Name', 'val']) df.to_sql(name='bmaster', con=engine, if_exists = 'replace', index=False)
user name password server databasename
Note :- Create dataframe as per the structure of the table.to_sql() method is used to write data from dataframe to mysql table. Standard library sqlalchemy is being used for writing data. Visit : python.mykvs.in for regular updates