我是靠谱客的博主 可爱黑夜,这篇文章主要介绍七周成为数据分析师学习笔记(第七周),现在分享给大家,希望可以做个参考。

一、Python连接数据库
1、安装pymysql
pip install pymysql
注意安装路径,注意环境切换
pip3 install pymysql(安装在python3下)
2、连接数据库

复制代码
1
2
3
4
5
6
7
8
9
10
import pymysql conn = pymysql.connect( host = 'localhost', # 127.0.0.1 user = 'root', password = '', db ='data'# 数据库名 port = 3306, charset = 'utf8' # 文本编码,gbk等 )

3、创建游标

复制代码
1
2
3
4
5
6
7
8
cur = conn.cursor() cur.execute('select * from data') # 执行select语句 data = cur.fetchall() for d in data: print(d) cur.close() # 关闭游标 conn.close() # 关闭数据库

4、pandas处理

复制代码
1
2
3
4
import pandas as pd sql = 'select * from company' pd.read_sql(sql, conn)# 旧版直接引用conn变量

新版:

复制代码
1
2
3
4
5
import sqlalchemy engine = sqlalchemy.creat_engine('mysql + pymysql://root:123456@localhost:3306/data?charset=uft8') # 格式:user:password@localhost:port/data_name?charset= pd.read_sql(sql, engine,)

数据筛选可以放服务器端用sql语句筛选,也可以读下来用pandas筛选

(二)写入数据库

复制代码
1
2
3
4
5
6
7
8
9
10
11
def reader(query, db) sql = query engine = sqlalchemy.creat_engine('mysql + pymysql://root:123456@localhost:3306/{0}?charset=uft8'.format(database))$ df = pd.read_sql(sql, engine,) return df df = reader('select * from data') df.to_sql(name = 'newtable', con = 'mysql + pymysql://root:123456@localhost:3306/data?charset=uft8', if _exists = 'fail', # append插入 index = False)

(三)注意事项
在数据库上建表,确定字段格式
从pandas传过来格式和预想不一样
if _exists= ‘append’,执行插入
index= True,没有预留列,有问题

换成csv格式to_csv

最后

以上就是可爱黑夜最近收集整理的关于七周成为数据分析师学习笔记(第七周)的全部内容,更多相关七周成为数据分析师学习笔记(第七周)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(82)

评论列表共有 0 条评论

立即
投稿
返回
顶部