扣丁学堂简述python3 pandas如何读取MySQL数据和插入

2018-07-24 13:44:46 371浏览

今天扣丁学堂Python培训小编和大家探讨一下python3 pandas如何读取MySQL数据和插入的问题,文章中会有详细的代码列出供大家参考,对Python开发感兴趣的小伙伴就随小编一起来了解一下吧。


扣丁学堂简述python3 pandas如何读取MySQL数据和插入


python 代码如下:


# -*- coding:utf-8 -*-
import pandas as pd
import pymysql
import sys
from sqlalchemy import create_engine

def read_mysql_and_insert():
 
 try:
  conn = pymysql.connect(host='localhost',user='user1',password='123456',db='test',charset='utf8')
 except pymysql.err.OperationalError as e:
  print('Error is '+str(e))
  sys.exit()
  
 try:
  engine = create_engine('mysql+pymysql://user1:123456@localhost:3306/test')
 except sqlalchemy.exc.OperationalError as e:
  print('Error is '+str(e))
  sys.exit()
 except sqlalchemy.exc.InternalError as e:
  print('Error is '+str(e))
  sys.exit()
  
 try: 
  sql = 'select * from sum_case'
  df = pd.read_sql(sql, con=conn) 
 except pymysql.err.ProgrammingError as e:
  print('Error is '+str(e))
  sys.exit() 

 print(df.head())
 df.to_sql(name='sum_case_1',con=engine,if_exists='append',index=False)
 conn.close()
 print('ok')
 
if __name__ == '__main__': 
 df = read_mysql_and_insert()


另外需要注意的还有。


1、test数据库里有两个表,建表语句如下:


CREATE TABLE `sum_case` ( 
 `type_id` tinyint(2) DEFAULT NULL, 
 `type_name` varchar(5) DEFAULT NULL, 
 KEY `b` (`type_name`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 
CREATE TABLE `sum_case_1` ( 
 `type_id` tinyint(2) DEFAULT NULL, 
 `type_name` varchar(5) DEFAULT NULL, 
 KEY `b` (`type_name`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 


插入初始数据:


insert into sum_case (type_id,type_name) values (1,'a'),(2,'b'),(3,'c') 


2、创建user1用户:


grant select, update,insert on test.* to 'user1'@'localhost' identified by '123456' 


以上就是扣丁学堂Python在线学习小编给大家分享的python3 pandas 读取MySQL数据和插入的实例,希望对小伙伴们有所帮助,想要了解更多内容的小伙伴可以登录扣丁学堂官网咨询。想要学好Python开发小编给大家推荐口碑良好的扣丁学堂,扣丁学堂有专业老师制定的Python学习路线图辅助学员学习,此外还有与时俱进的Python课程体系和大量的Python视频教程供学员观看学习,想要学好Python开发技术的小伙伴快快行动吧。扣丁学堂Python技术交流群:279521237。


扣丁学堂微信公众号

关注微信公众号获取更多学习资料



查看更多关于"Python开发资讯"的相关文章>



标签: 扣丁学堂Python培训 python3 pandas 读取MySQL数据和插入的实例 Python培训 Python视频教程 Python基础教程 python安装教程 Python核心编程 Python在线教程 Python在线视频 Python在线学习

热门专区

暂无热门资讯

课程推荐

微信
微博
15311698296

全国免费咨询热线

邮箱:codingke@1000phone.com

官方群:148715490

北京千锋互联科技有限公司版权所有   北京市海淀区宝盛北里西区28号中关村智诚科创大厦4层
京ICP备12003911号-6   Copyright © 2013 - 2019

京公网安备 11010802030908号