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实现从字典中删除元素的方法

本文实例讲述了python实现从字典中删除元素的方法。分享给大家供大家参考。具体分析如下: python的字典可以通过del方法进行元素删除,下面的代码详细演示了这一过程 # Cre...

django js实现部分页面刷新的示例代码

django js实现部分页面刷新的示例代码

例子中,我用的是显示机器上的进程信息的表格,获取不同的机器的进程信息时,更新这个展示信息的表格,如下: 当我在输入框中输入ip时,我希望只是更新这个表格,页面其他部分不变,实现方式如下...

Python3模拟登录操作实例分析

Python3模拟登录操作实例分析

本文实例讲述了Python3模拟登录操作。分享给大家供大家参考,具体如下: 模拟登录_要求: 1. 用户输入账号密码进行登录 2. 用户信息保存在文件内 3. 用户密码输入错误三次后锁定...

探究python中open函数的使用

探究python中open函数的使用

最近,开始学习python的开发,遇到了一点文件操作的问题,探究一下open函数的使用。 一、open()的函数原型 open(file, mode=‘r', buffering=-1,...

wxPython实现整点报时

本文实例为大家分享了wxPython整点报时的具体代码,供大家参考,具体内容如下 # C盘要有个wav文件,内含报时音频 import wx import...