python-mysqlHow can I convert a Python MySQL query into a pandas DataFrame?
To convert a Python MySQL query into a pandas DataFrame, first install the mysql-connector-python library. Then, create a connection to the MySQL database using the connect() method. After that, execute the SQL query using the execute() method. Finally, create a pandas.DataFrame() object and pass the result of the query to the DataFrame() constructor.
Example code
import mysql.connector
import pandas as pd
# create connection
connection = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="database"
)
# execute query
cursor = connection.cursor()
cursor.execute("SELECT * FROM table")
# create DataFrame
df = pd.DataFrame(cursor.fetchall())
Code explanation
import mysql.connector: imports the mysql-connector-python libraryconnection = mysql.connector.connect(): creates a connection to the MySQL databasecursor.execute("SELECT * FROM table"): executes the SQL querydf = pd.DataFrame(cursor.fetchall()): creates a pandas DataFrame object from the query result
Helpful links
More of Python Mysql
- How can I connect Python to a MySQL database?
- How do I connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database using an Xserver?
- How can I create a web application using Python and MySQL?
- How do Python and MySQL compare to MariaDB?
- How can I set a timeout for a MySQL connection in Python?
- How can I connect to MySQL using Python?
- How can I use Python and MySQL to create a login system?
- How do I use Python to connect to a MySQL database using XAMPP?
See more codes...