To connect to a database and query data, you need to install the following two libraries:
You can install these libraries using the following command in the command prompt or terminal:
pip install pandas
pip install sqlalchemy
Connecting to a database requires the following information:
You can use the following Python code to connect to the database:
from sqlalchemy import create_engine
# Connect to a MySQL database
engine = create_engine('mysql://username:password@hostname:port/databasename')
# Connect to a PostgreSQL database
engine = create_engine('postgresql://username:password@hostname:port/databasename')
# Connect to an Oracle database, requires cx_Oracle library to be installed
engine = create_engine('oracle+cx_oracle://username:password@hostname:port/databasename')
Use the read_sql function from pandas to query data from the database. The read_sql function requires two parameters:
Here is an example of querying data:
import pandas as pd
# Execute SQL query and store the result in a DataFrame
df = pd.read_sql('SELECT * FROM mytable', engine)
# Print the DataFrame
print(df)
Thank you for taking the time to explore data-related insights with me. I appreciate your engagement. If you find this information helpful, I invite you to follow me or connect with me on LinkedIn or X(@Luca_DataTeam). Happy exploring!👋