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

yipeiwu_com6年前Python基础

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数据和插入的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在Python的Django框架中编写错误提示页面

你应该在生产环境中把TEMPLATE_DEBUGFalse 如果这个设为`` True`` ,为了在那个好看的错误页面上显示足够的东西,Django的模版系统就会为每一个模版保存一些额外...

Python数据集切分实例

Python数据集切分实例

在处理数据过程中经常要把数据集切分为训练集和测试集,因此记录一下切分代码。 ''' data:数据集 test_ratio:测试机占比 如果data为numpy.numpy.ndar...

python numpy数组复制使用实例解析

这篇文章主要介绍了python numpy数组复制使用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在使用python时我们...

python实现输入的数据在地图上生成热力图效果

我就废话不多说了,直接贴代码,注意要先安装folium #-*-coding:utf8-*- #输入data生成热力图html,借助了leaflet,没网不能用 import o...

python 解决flask uwsgi 获取不到全局变量的问题

问题 在写flask,使用uwsgi启动的时候,涉及到多request线程访问同一个全局变量,发现不能获取到全局变量的值的修改,这在flask独立启动的时候是没有问题的。 伪代码 全局变...