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 do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How do I use Python to update multiple columns in a MySQL database?
- How do I use Python to show the MySQL processlist?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How do Python and MySQL compare to MariaDB?
- How can I convert a MySQL query result to a Python dictionary?
- How do I connect to a MySQL database using XAMPP and Python?
- How can I use Python to perform an upsert on a MySQL database?
See more codes...