python3 pandas 读取MySQL数据和插入的实例
更新时间:2018年04月20日 10:46:57 作者:徐三少北
下面小编就为大家分享一篇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'
以上这篇python3 pandas 读取MySQL数据和插入的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Python2到Python3的迁移过程中报错AttributeError: ‘str‘ objec
在 Python 编程过程中,AttributeError: 'str' object has no attribute 'decode' 是一个常见的错误,这通常会在处理字符串时出现,尤其是在 Python 2 到 Python 3 的迁移过程中,本文将详细介绍该问题的根源,并提供解决方案,需要的朋友可以参考下2025-04-04
Pycharm主题切换(禁用)导致UI界面显示异常的解决方案
这篇文章主要介绍了Pycharm主题切换(禁用)导致UI界面显示异常的原因分析和解决方案,文中通过图文结合的方式给大家介绍的非常详细,需要的朋友可以参考下2024-06-06
PyTorch 中的 torch.utils.data 解析(推荐)
这篇文章主要介绍了PyTorch torch.utils.data.Dataset概述案例详解,主要介绍对 torch.utils.data.Dataset 的理解,需要的朋友可以参考下2023-02-02


最新评论