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

yipeiwu_com5年前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字符编码判断方法分析

本文实例讲述了Python字符编码判断方法。分享给大家供大家参考,具体如下: 方法一: isinstance(s, str) 用来判断是否为一般字符串 isinstance(s, uni...

python验证码识别实例代码

本文研究的主要是Python验证码识别的相关代码,具体如下。 Talk is cheap, show you the Code! import numpy as np import...

python内存管理分析

python内存管理分析

本文较为详细的分析了python内存管理机制。分享给大家供大家参考。具体分析如下: 内存管理,对于Python这样的动态语言,是至关重要的一部分,它在很大程度上甚至决定了Python的执...

理解Python垃圾回收机制

一.垃圾回收机制 Python中的垃圾回收是以引用计数为主,分代收集为辅。引用计数的缺陷是循环引用的问题。 在Python中,如果一个对象的引用数为0,Python虚拟机就会回收这个对象...

python 3.6.4 安装配置方法图文教程

python 3.6.4 安装配置方法图文教程

今天补一下关于如何安装Python的操作步骤: 我的系统是我win系统 64 位 1.第一步先去python的官方网站下载python的安装包:地址 根据自己的系统选择对应的...