第十章用Python获取sqlite、MySQL、Excel、csv、json中的数据

2023-05-10,,

目录

获取sqlite3中的数据
sqlite3库获取sqlite数据
pandas库获取sqlite数据
获取MySQL中的数据
pymsql库获取MySQL数据
pandas库获取mysql数据
获取Excel中的数据
xlrd库获取Excel数据
pandas库获取Excel数据
获取csv中的数据
csv库读取csv数据
pandas读取csv数据
获取json中的数据
json库读取json数据
pandas读取json数据
源码地址

本文可以学习到以下内容:

    用Python、pandas获取sqlite3中的数据
    用Python、pandas获取MySQL中的数据
    用Python、pandas获取Excel、csv、json中的数据

获取sqlite3中的数据

sqlite3是一个很轻量级C语言库,可以提供一种基于磁盘的数据库。在浏览器、手机、电子设备中广泛使用。
我们可以用SQL语句查询数据,还可以用Python操作sqlite3数据库对数据进行查询。

sqlite3库获取sqlite数据

import sqlite3
# 创建一个连接对象,连接上上级目录下的 data.db 数据库
conn = sqlite3.connect("../data.db")
# 创建一个游标对象,操作数据库中的数据
c = conn.cursor()
# 执行 SQL 语句查询数据
sql = "select * FROM salesSummary limit 5;"
result = c.execute(sql)
# 查看数据
for r in result:
print(r)
# 数据操作完成后,需要关闭数据库的连接
conn.close()

将此操作封装为函数:

def get_sqlite3_data(sql,db_path="../data.db"):
conn = sqlite3.connect(db_path)
c = conn.cursor()
# 将数据保存到列表中
result = [r for r in c.execute(sql)]
conn.close()
return result

调用函数:

sql = "select * FROM salesSummary limit 5;"
result = get_sqlite3_data(sql)
print(result)

pandas库获取sqlite数据

pandas读取sqlite3数据需要用到sqlalchemy库
sqlalchemy官网地址:https://www.osgeo.cn/sqlalchemy/
pandas的read_sql方法通过sql语言获取数据

import os
import pandas as pd
import numpy as np
from sqlalchemy import create_engine # 数据库地址:数据库放在上一级目录下
db_path = os.path.join(os.path.dirname(os.getcwd()),"data.db")
engine_path = "sqlite:///"+db_path # 获取数据函数,根据输入的SQL语句返回 DataFrame 类型数据
def link_sqlite(sql):
engine = create_engine(engine_path)
df = pd.read_sql(sql,con=engine)
return df sql = "select * from salesSummary"
df = link_sqlite(sql) # 查看数据前5条数据
df.head()

获取MySQL中的数据

MySQL是个人和中小型企业常用的关系型数据库
体积小、速度快、成本低,开放源码
python读取没有MySQL需要安装 pymysql 第三方库

pip install pymysql

pymsql库获取MySQL数据

import pymysql

host = "127.0.0.1"
port=3306
user="user"
password="password"
database="database" conn = pymysql.connect(
host=host,
port=port,
user=user,
password=password,
database=database
) cursor = conn.cursor() sql = "select * from country limit 5;"
cursor.execute(sql) cursor.fetchone() conn.close()

将此操作封装为函数使用:

import pymysql

host = "127.0.0.1"
port=3306
user="user"
password="password"
database="database" def get_mysql_data(sql):
conn = pymysql.connect(host=host,port=port,user=user,password=password,database=database)
cursor = conn.cursor()
cursor.execute(sql)
result = [r for r in cursor.fetchall()]
conn.close()
return result

pandas库获取mysql数据

官方文档:https://docs.sqlalchemy.org/en/20/intro.html
需要先安装 SQLAlchemy和pymysql第三方库

from sqlalchemy import create_engine
# 当密码中有特殊符合时:@!@#$%^&*(),需要处理一下
from urllib.parse import quote_plus as urlquote host = "127.0.0.1"
port=3306
user="user"
password="password"
database="database"
url = f"mysql+pymysql://{user}:{urlquote(password)}@{host}:{port}/{database}" engine = create_engine(url=url) sql = "select * from country limit 5;"
df = pd.read_sql(sql,con=engine)

获取Excel中的数据

Excel是一款电子表格软件,出色的计算功能和图表工具
Python获取Excel数据需要安装 xlrd 库
文档地址:https://xlrd.readthedocs.io/en/latest/

pip install xlrd

xlrd库获取Excel数据

import xlrd

# 打开指定的Excel文件
workbook = xlrd.open_workbook("../数据源/省市区adcode与经纬度映射表.xlsx") # Excel文件中的工作薄数量
sheet_num = workbook.nsheets
# Excel 文件中工作薄名字
sheet_name = workbook.sheet_names() # 打开第一个工作簿
sheet = workbook.sheet_by_index(0)
# 工作薄名字
sh_name = sheet.name
# 工作簿行数
sh_rows = sheet.nrows
# 工作簿列数
sh_cols = sheet.nclos # 获取指定单元格的数据
cell = sheet.cell_value(rowx=29,colx=3)
# 获取一行数据
row_value = sheet.row(0)
# 获取一列数据
col_value = sheet.col(0) print(sheet_name,sh_name,sh_rows,sh_cols,cell,row_value)
print(col_value)

pandas库获取Excel数据

pandas使用read_excel方法获取Excel数据

import numpy as np
import pandas as pd df= pd.read_excel("../数据源/省市区adcode与经纬度映射表.xlsx") df.head()

获取csv中的数据

csv以纯文本形式存储表格数据,已字符分割不同值
CSV是一种通用的、相对简单的文件格式,被用户、商业和科学广泛应用
Python内置的csv模块可以读取csv数据

csv库读取csv数据

import csv

with open("../数据源/sale.csv",encoding="gbk") as f:
f_csv = csv.reader(f)
header = next(f_csv)
print(header)
for r in f_csv:
print(r)

pandas读取csv数据

pandas的read_csv方法获取数据

import numpy as np
import pandas as pd df= pd.read_csv("../数据源/earphone_sentiment.csv")

获取json中的数据

json是一种轻量级的数据交换格式
简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言
Python内置的json模块可以读取csv数据

json库读取json数据

import json

with open("../数据源/商品销售额.json") as f:
json_data = json.load(f)
print(json_data)

pandas读取json数据

pandas中的read_json方法获取数据

import numpy as np
import pandas as pd df = pd.read_json("../数据源/商品销售额.json")

源码地址

链接:https://pan.baidu.com/s/1Ii5YEaShfx6jF9AbQ52FYQ?pwd=r4mf
提取码:r4mf

第十章用Python获取sqlite、MySQL、Excel、csv、json中的数据的相关教程结束。

《第十章用Python获取sqlite、MySQL、Excel、csv、json中的数据.doc》

下载本文的Word格式文档,以方便收藏与打印。