python3 pandas 读取MySQL数据和插入的实例
python代码如下:
#-*-coding:utf-8-*- importpandasaspd importpymysql importsys fromsqlalchemyimportcreate_engine defread_mysql_and_insert(): try: conn=pymysql.connect(host='localhost',user='user1',password='123456',db='test',charset='utf8') exceptpymysql.err.OperationalErrorase: print('Erroris'+str(e)) sys.exit() try: engine=create_engine('mysql+pymysql://user1:123456@localhost:3306/test') exceptsqlalchemy.exc.OperationalErrorase: print('Erroris'+str(e)) sys.exit() exceptsqlalchemy.exc.InternalErrorase: print('Erroris'+str(e)) sys.exit() try: sql='select*fromsum_case' df=pd.read_sql(sql,con=conn) exceptpymysql.err.ProgrammingErrorase: print('Erroris'+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数据库里有两个表,建表语句如下:
CREATETABLE`sum_case`( `type_id`tinyint(2)DEFAULTNULL, `type_name`varchar(5)DEFAULTNULL, KEY`b`(`type_name`) )ENGINE=InnoDBDEFAULTCHARSET=utf8;
CREATETABLE`sum_case_1`( `type_id`tinyint(2)DEFAULTNULL, `type_name`varchar(5)DEFAULTNULL, KEY`b`(`type_name`) )ENGINE=InnoDBDEFAULTCHARSET=utf8;
插入初始数据
insertintosum_case(type_id,type_name)values(1,'a'),(2,'b'),(3,'c')
2)创建user1用户
grantselect,update,insertontest.*to'user1'@'localhost'identifiedby'123456'
以上这篇python3pandas读取MySQL数据和插入的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。