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'
相关推荐
CloudXli 2020-06-04
JamesRayMurphy 2020-05-31
chuckchen 2020-10-31
Will0 2020-10-12
Dreamhome 2020-10-09
xirongxudlut 2020-09-28
星辰大海的路上 2020-09-13
chaochao 2020-08-31
猪猪侠喜欢躲猫猫 2020-08-17
快递小可 2020-08-16
shengge0 2020-07-26
巩庆奎 2020-07-21
张文倩数据库学生 2020-07-19
xirongxudlut 2020-07-18
Ericbig 2020-07-18
kyelu 2020-07-09
liangzhouqu 2020-07-07
GuoSir 2020-06-28