Code前端首页关于Code前端联系我们

Python数据科学教程:sqlalchemy 连接到关系数据库并使用SQL的全部功能

terry 2年前 (2023-09-25) 阅读数 45 #后端开发

连接到关系数据库并使用Pandas 库和其他库来实现数据库连接来分析数据。这个包称为 sqlalchemy,提供在 python 中使用的完整 SQL 功能。

安装 SQLAlchemy

使用安装 Pandas 环境章节中描述的 Anaconda 进行安装非常简单。假设您已按照本章中的说明安装了 Anaconda,请在 Anaconda 提示符下运行以下命令来安装 SQLAlchemy 包。

conda install sqlalchemy
Shell

读取关系表

我们将使用Sqlite3作为关系数据库,因为它非常轻量且易于使用。尽管SQLAlchemy库可以连接到许多关系源,包括MySql、Oracle和Postgresql,以及Mssql。首先,我们创建数据库引擎,然后使用 SQLAlchemy 库的 to_sql 函数连接到数据库引擎。

在下面的示例中,我们在通过读取 csv 文件创建的数据框中使用 to_sql 函数创建一个关系表。然后使用 Pandas 中的函数 read_sql_query 运行并捕获各种 SQL 查询的结果。

from sqlalchemy import create_engine
import pandas as pd

data = pd.read_csv('/path/input.csv')

# Create the db engine
engine = create_engine('sqlite:///:memory:')

# Store the dataframe as a table
data.to_sql('data_table', engine)

# Query 1 on the relational table
res1 = pd.read_sql_query('SELECT * FROM data_table', engine)
print('Result 1')
print(res1)
print('')

# Query 2 on the relational table
res2 = pd.read_sql_query('SELECT dept,sum(salary) FROM data_table group by dept', engine)
print('Result 2')
print(res2)
Shell

运行上面的示例代码,得到以下结果-

Result 1
   index  id    name  salary  start_date        dept
0      0   1    Rick  623.30  2012-01-01          IT
1      1   2     Dan  515.20  2013-09-23  Operations
2      2   3   Tusar  611.00  2014-11-15          IT
3      3   4    Ryan  729.00  2014-05-11          HR
4      4   5    Gary  843.25  2015-03-27     Finance
5      5   6   Rasmi  578.00  2013-05-21          IT
6      6   7  Pranab  632.80  2013-07-30  Operations
7      7   8    Guru  722.50  2014-06-17     Finance

Result 2
         dept  sum(salary)
0     Finance      1565.75
1          HR       729.00
2          IT      1812.30
3  Operations      1148.00
Shell

将数据插入关系表

你也可以使用pandas中的❙exe※exe来插入数据Insert into关系表。在下面的代码中,我们将之前的 csv 文件作为输入数据集,将其存储在关系表中,然后使用 sql.execute 插入另一条记录。

from sqlalchemy import create_engine
from pandas.io import sql

import pandas as pd

data = pd.read_csv('C:/Users/Rasmi/Documents/pydatasci/input.csv')
engine = create_engine('sqlite:///:memory:')

# Store the Data in a relational table
data.to_sql('data_table', engine)

# Insert another row
sql.execute('INSERT INTO data_table VALUES(?,?,?,?,?,?)', engine, params=[('id',9,'Ruby',711.20,'2015-03-27','IT')])

# Read from the relational table
res = pd.read_sql_query('SELECT ID,Dept,Name,Salary,start_date FROM data_table', engine)
print(res)
Shell

运行上面的示例代码,得到以下代码 -

   id        dept    name  salary  start_date
0   1          IT    Rick  623.30  2012-01-01
1   2  Operations     Dan  515.20  2013-09-23
2   3          IT   Tusar  611.00  2014-11-15
3   4          HR    Ryan  729.00  2014-05-11
4   5     Finance    Gary  843.25  2015-03-27
5   6          IT   Rasmi  578.00  2013-05-21
6   7  Operations  Pranab  632.80  2013-07-30
7   8     Finance    Guru  722.50  2014-06-17
8   9          IT    Ruby  711.20  2015-03-27
Shell

删除关系表中的数据

也可以使用

exe pandas 函数来删除数据删除到关系表。下面的代码将根据给定的输入条件删除一行。

from sqlalchemy import create_engine
from pandas.io import sql

import pandas as pd

data = pd.read_csv('C:/Users/Rasmi/Documents/pydatasci/input.csv')
engine = create_engine('sqlite:///:memory:')
data.to_sql('data_table', engine)

sql.execute('Delete from data_table where name = (?) ', engine,  params=[('Gary')])

res = pd.read_sql_query('SELECT ID,Dept,Name,Salary,start_date FROM data_table', engine)
print(res)
Python

运行上面的代码示例,得到以下结果 -

   id        dept    name  salary  start_date
0   1          IT    Rick   623.3  2012-01-01
1   2  Operations     Dan   515.2  2013-09-23
2   3          IT   Tusar   611.0  2014-11-15
3   4          HR    Ryan   729.0  2014-05-11
4   6          IT   Rasmi   578.0  2013-05-21
5   7  Operations  Pranab   632.8  2013-07-30
6   8     Finance    Guru   722.5  2014-06-17

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门