python3 pandas 读取MySQL数据和插入 python3 pandas 读取MySQL数据和插入的实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python3 pandas 读取MySQL数据和插入 python3 pandas 读取MySQL数据和插入的实例

徐三少北   2021-03-28 我要评论
想了解python3 pandas 读取MySQL数据和插入的实例的相关内容吗,徐三少北在本文为您仔细讲解python3 pandas 读取MySQL数据和插入的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:python,pandas读取,下面大家一起来学习吧。

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' 

以上这篇python3 pandas 读取MySQL数据和插入的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们