How to read data from a database using pandas?

To read data from a database using pandas, you first need to establish a connection to the database and then use the read_sql_query function from pandas to retrieve the data. Here is an example code:

import pandas as pd
import sqlite3

# 连接到数据库
conn = sqlite3.connect('database.db')

# 使用pandas读取数据库中的数据
query = "SELECT * FROM table_name"
df = pd.read_sql_query(query, conn)

# 打印读取的数据
print(df)

# 关闭数据库连接
conn.close()

In the code above, the database is first connected using the sqlite3 library, then an SQL query is executed and the results are stored in a DataFrame object using the read_sql_query function of pandas. Finally, the DataFrame object is printed to view the retrieved data, and the database connection is closed. Depending on the type of database, the method of connecting to it may vary and adjustments may be necessary accordingly.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds