Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Reading SQL Databases

Pandas Reading SQL Databases

Pandas provides a set of functions that interact directly with SQL databases, allowing query results to be read directly as DataFrames and DataFrames to be written back to the database. This frees data analysts from manually handling database connections and result parsing, greatly simplifying the interaction between databases and Python.


Overview of Core Functions

function Purpose Return Type
pd.read_sql() Execute a SQL query or read an entire table (a general-purpose function compatible with both scenarios) DataFrame
pd.read_sql_query() Execute a SQL query statement, suitable for complex queries DataFrame
pd.read_sql_table() Read an entire table directly, only supports SQLAlchemy connections DataFrame
DataFrame.to_sql() Write a DataFrame to a database table None / int

In practical work, it is recommended to use pd.read_sql(), which automatically determines whether to execute a query or read an entire table based on the passed parameters, offering the best compatibility.pd.read_sql_table() Only SQLAlchemy engine connections are supported; native sqlite3 DB-API connections such as sqlite3 are not supported.


Establish a database connection

Pandas itself does not connect to databases directly; you need to use a third-party library to establish a connection and pass it in. There are two mainstream approaches:SQLAlchemy engine(recommended) and native DB-API connection(lightweight and simple).

Method 1: SQLAlchemy (recommended)

SQLAlchemy is the most mainstream database toolkit in Python, supporting all major databases and offering the best compatibility with Pandas:

pip install sqlalchemy

Example

from

sqlalchemy

import

create_engine

SQLAlchemy connection string format: database type + driver://username:password@host:port/database name

SQLite (file-based database, no username or password required)

engine

=

create_engine

(

"sqlite:///mydata.db"

)

MySQL

engine

=

create_engine

(

"mysql+pymysql://root:password@localhost:3306/mydb"

)

PostgreSQL

engine

=

create_engine

(

"postgresql+psycopg2://user:password@localhost:5432/mydb"

)

SQL Server

engine

=

create_engine

(

"mssql+pyodbc://user:password@server/mydb?driver=ODBC+Driver+17+for+SQL+Server"

)

Verify whether the connection is successful

with

engine.

connect

(

)

as

conn:

   

print

(

"Connection successful"

)

Method 2: native sqlite3 connection (SQLite only)

Python built-in sqlite3 module, no extra installation required, suitable for lightweight local SQLite databases:

Example

import

sqlite3

Connect to a SQLite file database (created automatically if the file does not exist)

conn

=

sqlite3.

connect

(

"mydata.db"

)

Connect to an in-memory database (data disappears when the program exits, suitable for testing)

conn_memory

=

sqlite3.

connect

(

":memory:"

)

The connection must be closed manually after use

conn.close()


Reading data with pd.read_sql()

Basic Syntax

pd.read_sql(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None)

Description of main parameters:

Parameters Type Description
sql str SQL query statement, or table name (related to con the type)
con Connection object SQLAlchemy engine or DB-API connection object
index_col str or list Set the specified column as the DataFrame's row index
params list or dict Parameter values for SQL parameterized queries, to prevent SQL injection
parse_dates list or dict Parse the specified column as datetime type
chunksize int Read in chunks, returning an iterator of DataFrames with the specified number of rows per chunk

1. Read an Entire Table

Example

import

pandas

as

pd

from

sqlalchemy

import

create_engine

engine

=

create_engine

(

"sqlite:///mydata.db"

)

Read the entire employees table

df

=

pd.

read_sql

(

"employees"

,

con

=

engine

)

print

(

df.

head

(

)

)

print

(

f

"{len(df)} rows, {len(df.columns)} columns in total"

)

2. Execute a SQL Query

Example

import

pandas

as

pd

from

sqlalchemy

import

create_engine

engine

=

create_engine

(

"sqlite:///mydata.db"

)

Query with conditions

df

=

pd.

read_sql

(

"SELECT * FROM employees WHERE department = 'IT'"

,

con

=

engine

)

Multi-table join query

sql

=

"""
    SELECT e.name, e.salary, d.department_name
    FROM employees e
    JOIN departments d ON e.dept_id = d.id
    WHERE e.salary > 10000
    ORDER BY e.salary DESC
"""

df

=

pd.

read_sql

(

sql

,

con

=

engine

)

print

(

df.

head

(

10

)

)

3. Parameterized Queries (Prevent SQL Injection)

When query conditions come from user input,be sure to use parameterized queries, do not concatenate strings into SQL:

Example

import

pandas

as

pd

from

sqlalchemy

import

create_engine

engine

=

create_engine

(

"sqlite:///mydata.db"

)

Unsafe practice: concatenating strings into SQL, which risks SQL injection

dept

=

"IT"

df = pd.read_sql(f"SELECT * FROM employees WHERE department = '{dept}'", engine)

Safe practice: use ? placeholders (sqlite3) or :name named parameters (SQLAlchemy)

SQLite / DB-API style (using ?)

df

=

pd.

read_sql

(

   

"SELECT * FROM employees WHERE department = ? AND salary > ?"

,

    con

=

engine

,

    params

=

[

"IT"

,

8000

]

 

params is a list, replacing ? by position

)

SQLAlchemy named parameter style (using :param_name)

from

sqlalchemy

import

text

with

engine.

connect

(

)

as

conn:

    df

=

pd.

read_sql

(

        text

(

"SELECT * FROM employees WHERE department = :dept AND salary > :min_salary"

)

,

        con

=

conn

,

        params

=

{

"dept"

:

"IT"

,

"min_salary"

:

8000

}

   

)

print

(

df

)

4. Set the Index Column

Example

import

pandas

as

pd

from

sqlalchemy

import

create_engine

engine

=

create_engine

(

"sqlite:///mydata.db"

)

Set the id column in the database as the DataFrame's row index

df

=

pd.

read_sql

(

"SELECT * FROM employees"

,

con

=

engine

,

index_col

=

"id"

)

print

(

df.

head

(

)

)

Use multiple columns as a composite index

df

=

pd.

read_sql

(

   

"SELECT * FROM orders"

,

    con

=

engine

,

    index_col

=

[

"year"

,

"month"

]

 

Composite index

)

5. Parse Date Columns

Date fields stored in the database are read as strings by default; use the parse_dates parameter to parse them directly as datetime:

Example

import

pandas

as

pd

from

sqlalchemy

import

create_engine

engine

=

create_engine

(

"sqlite:///mydata.db"

)

Parse the created_at and updated_at columns as datetime type

df

=

pd.

read_sql

(

   

"SELECT * FROM orders"

,

    con

=

engine

,

    parse_dates

=

[

"created_at"

,

"updated_at"

]

)

print

(

df.

dtypes

)

created_at    datetime64[ns]

updated_at    datetime64[ns]

You can also specify a parse format (for non-standard date formats)

df

=

pd.

read_sql

(

   

"SELECT * FROM orders"

,

    con

=

engine

,

    parse_dates

=

{

"created_at"

:

"%Y%m%d"

}

 

Parse a format like "20240115" as a date

)


Reading Large Data in Chunks (chunksize)

When a database table is very large, reading it all into memory at once causes OOM (out of memory). Use the chunksize parameter to read data in batches, processing only a portion at a time:

Example

import

pandas

as

pd

from

sqlalchemy

import

create_engine

engine

=

create_engine

(

"mysql+pymysql://root:password@localhost/bigdata"

)

chunksize=10000 means reading 10000 rows at a time, returning an iterator

chunks

=

pd.

read_sql

(

"SELECT * FROM large_table"

,

con

=

engine

,

chunksize

=

10000

)

Process chunk by chunk (only 10000 rows in memory at a time)

result_list

=

[

]

for

i

,

chunk

in

enumerate

(

chunks

)

:

   

Apply processing logic to each chunk (such as filtering, aggregation, etc.)

    processed

=

chunk

[

chunk

[

"status"

]

==

"active"

]

    result_list.

append

(

processed

)

   

print

(

f

"Processed chunk {i+1}, valid rows in current chunk: {len(processed)}"

)

Concatenate all processed chunks into one DataFrame

final_df

=

pd.

concat

(

result_list

,

ignore_index

=

True

)

print

(

f

"Finally, {len(final_df)} rows of valid data in total"

)


pd.read_sql_query() and pd.read_sql_table()

pd.read_sql_query(): executes queries only

The difference between pd.read_sql() Its functionality is basically the same, but it only accepts SQL query statements, not table names. The parameters are completely identical, making it suitable for scenarios that need to clearly distinguish "query" from "read table" operations:

Example

import

pandas

as

pd

from

sqlalchemy

import

create_engine

engine

=

create_engine

(

"sqlite:///mydata.db"

)

df

=

pd.

read_sql_query

(

   

"SELECT name, salary FROM employees WHERE salary > 5000"

,

    con

=

engine

)

print

(

df

)

pd.read_sql_table(): reads an entire table (SQLAlchemy only)

pd.read_sql_table() Specifically for reading an entire table, supports filtering columns and rows via parameters, butonly supports SQLAlchemy engine connections, does not support native connections such as sqlite3:

Example

import

pandas

as

pd

from

sqlalchemy

import

create_engine

engine

=

create_engine

(

"sqlite:///mydata.db"

)

Read specified columns of the employees table

df

=

pd.

read_sql_table

(

   

"employees"

,

    con

=

engine

,

    columns

=

[

"id"

,

"name"

,

"salary"

,

"department"

]

 

Read only these columns

)

You can also specify a schema (a mode in the database)

df

=

pd.

read_sql_table

(

   

"employees"

,

    con

=

engine

,

    schema

=

"hr"

   

Read the employees table under the hr schema

)

print

(

df.

head

(

)

)


Writing a DataFrame to a Database (to_sql)

Use DataFrame.to_sql() You can write a DataFrame to a database, supporting creating a new table, appending data, or overwriting an existing table:

Basic Syntax

DataFrame.to_sql(name, con, schema=None, if_exists='fail', index=True, index_label=None, chunksize=None, dtype=None, method=None)

if_exists The parameter determines the behavior when the target table already exists:

if_exists values Behavior Applicable scenarios
'fail'(default) Raise an error when the table already exists Prevent accidental overwriting of existing data
'replace' Drop the original table first, then recreate it and write Full refresh of data
'append' Append data to an existing table without changing its structure Incrementally write new data

Example

import

pandas

as

pd

from

sqlalchemy

import

create_engine

engine

=

create_engine

(

"sqlite:///mydata.db"

)

Prepare sample data

df

=

pd.

DataFrame

(

{

   

"name"

:

[

"Zhang San"

,

"Li Si"

,

"Wang Wu"

]

,

   

"department"

:

[

"IT"

,

"HR"

,

"IT"

]

,

   

"salary"

:

[

12000

,

8000

,

15000

]

}

)

Write the DataFrame to the employees table, replacing it if it already exists

df.

to_sql

(

   

"employees"

,

    con

=

engine

,

    if_exists

=

"replace"

,

 

Overwrite the original data

    index

=

False

         

Do not write the DataFrame's row index to the database (usually unnecessary)

)

Append new data to an existing table (note: column names and data types must match)

new_employees

=

pd.

DataFrame

(

{

   

"name"

:

[

"Zhao Liu"

]

,

   

"department"

:

[

"Finance"

]

,

   

"salary"

:

[

11000

]

}

)

new_employees.

to_sql

(

"employees"

,

con

=

engine

,

if_exists

=

"append"

,

index

=

False

)

Verify the write result

result

=

pd.

read_sql

(

"SELECT * FROM employees"

,

con

=

engine

)

print

(

result

)

specify the data types of columns

When writing, you can use the dtype parameter to explicitly specify the type of each column in the database:

Example

import

pandas

as

pd

from

sqlalchemy

import

create_engine

,

Integer

,

String

,

Float

,

DateTime

engine

=

create_engine

(

"sqlite:///mydata.db"

)

df

=

pd.

DataFrame

(

{

   

"id"

:

[

1

,

2

,

3

]

,

   

"name"

:

[

"Alice"

,

"Bob"

,

"Charlie"

]

,

   

"score"

:

[

92.5

,

88.0

,

95.3

]

,

}

)

df.

to_sql

(

   

"students"

,

    con

=

engine

,

    if_exists

=

"replace"

,

    index

=

False

,

    dtype

=

{

       

"id"

:    Integer

(

)

,

 

Integer type

       

"name"

:  String

(

50

)

,

 

Variable-length string, up to 50 characters

       

"score"

: Float

(

)

     

Float (floating point number)

   

}

)


Complete Usage Example

Below is a complete example of reading sales data from a SQLite database and analyzing it:

Example

import

pandas

as

pd

import

sqlite3

from

sqlalchemy

import

create_engine

Step 1: Prepare the test database

engine

=

create_engine

(

"sqlite:///sales.db"

)

conn

=

sqlite3.

connect

(

"sales.db"

)

Create sample data and write it to the database

sales_data

=

pd.

DataFrame

(

{

   

"order_id"

:  

[

1001

,

1002

,

1003

,

1004

,

1005

,

1006

]

,

   

"product"

:    

[

"Notebook"

,

"Phone"

,

"Tablet"

,

"Notebook"

,

"Phone"

,

"Tablet"

]

,

   

"amount"

:    

[

6999

,

3999

,

2999

,

7299

,

4299

,

3199

]

,

   

"quantity"

:  

[

2

,

5

,

3

,

1

,

4

,

2

]

,

   

"order_date"

:

[

"2024-01-10"

,

"2024-01-15"

,

"2024-01-20"

,

                   

"2024-02-05"

,

"2024-02-10"

,

"2024-02-18"

]

}

)

sales_data.

to_sql

(

"sales"

,

con

=

engine

,

if_exists

=

"replace"

,

index

=

False

)

Step 2: Read the data and parse dates

df

=

pd.

read_sql

(

   

"SELECT * FROM sales"

,

    con

=

engine

,

    parse_dates

=

[

"order_date"

]

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

Step 3: Compute sales by product

sql_agg

=

"""
    SELECT product,
           COUNT(*) AS order_count,
           SUM(amount * quantity) AS total_sales,
           AVG(amount) AS avg_unit_price
    FROM sales
    GROUP BY product
    ORDER BY total_sales DESC
"""

summary

=

pd.

read_sql

(

sql_agg

,

con

=

engine

)

print

(

"Sales Summary by Product:"

)

print

(

summary

)

print

(

)

Step 4: Write the results back to the database

summary.

to_sql

(

"sales_summary"

,

con

=

engine

,

if_exists

=

"replace"

,

index

=

False

)

print

(

"Summary data has been written to the sales_summary table"

)

conn.

close

(

)

The execution result of the code above is:



Original data:

   order_id product  amount  quantity order_date

0      1001     笔记本    6999         2 2024-01-10

1      1002      手机    3999         5 2024-01-15

2      1003      平板    2999         3 2024-01-20

3      1004     笔记本    7299         1 2024-02-05

4      1005      手机    4299         4 2024-02-10

5      1006      平板    3199         2 2024-02-18



Product sales summary:

  product  订单数  总销售额   平均单价

0     手机    2   36991   4149.0

1    笔记本    2   21297   7149.0

2     平板    2   15395   3099.0



汇总数据已写入 sales_summary 表


Common Issues and Notes

1. Close Connections After Use

When using native DB-API connections (such as sqlite3), the connection must be closed manually after operations. It is recommended to use a with statement for automatic management:

Example

import

sqlite3

import

pandas

as

pd

Use a with statement to automatically close the connection on exit, so the connection is not leaked even if an exception occurs

with

sqlite3.

connect

(

"mydata.db"

)

as

conn:

    df

=

pd.

read_sql

(

"SELECT * FROM employees"

,

con

=

conn

)

print

(

df

)

 

The connection has been closed automatically, but the df data is still available

2. Do Not Read All Data from Large Tables Directly

For large tables with millions of rows or more, directly SELECT * reading all the data will exhaust memory. You should filter data at the SQL level first (WHERE, LIMIT), or use chunksize chunked reading.

3. read_sql_table Only Supports SQLAlchemy

If you use a native DB-API connection such as sqlite3 to call it, pd.read_sql_table()an error will be raised. NotImplementedErrorPlease use read_sql_query instead, pd.read_sql() or switch to a SQLAlchemy engine.

4. The index Parameter of to_sql Defaults to True

By default to_sql It will also write the DataFrame's row index (0, 1, 2...) to the database, forming a column named index , which is usually redundant. It is recommended to explicitly pass index=False。

5. Database Drivers Must Be Installed Separately

When SQLAlchemy connects to different databases, the corresponding driver packages must also be installed:

Database Driver package Install Command
MySQL PyMySQL pip install pymysql
PostgreSQL psycopg2 pip install psycopg2-binary
SQL Server pyodbc pip install pyodbc
Oracle cx_Oracle pip install cx_Oracle
SQLite built-in No installation needed