1. 程式人生 > 其它 >通過python操作資料庫

通過python操作資料庫

1.python複製表

複製表語句:

create table newtable like oldtable;

insert intonewtable select * from oldtable;​

注:newtable:要複製的新表

  oldtable:資料庫中存在的表

python程式碼:

import pymysql
conn = pymysql.connect(host='ares-m.dbsit.sfcloud.local', port=3306, database='ares', user='ares', password='7i6opxMmkj', charset='utf8
') cursor = conn.cursor() cursor.execute('create table tt_flight_execute_flow12 like tt_flight_execute_flow;') cursor.execute('insert into tt_flight_execute_flow12 select * from tt_flight_execute_flow;') conn.commit() conn.close()

2.將xls中資料匯入資料庫

需要使用pandas庫和sqlalchemy

python程式碼:

import pandas as pd
from sqlalchemy import create_engine import pymysql pymysql.install_as_MySQLdb() #讀取檔案資料 data1 = pd.read_excel(r"D:\user\01401692\Downloads\tt_flight_execute_flow.xls") conn = create_engine("mysql+pymysql://ares:[email protected]:3306/ares?charset=utf8") #匯入資料庫資料 pd.io.sql.to_sql(data1, '
tt_flight_execute_flow_copy0713', conn, schema='ares', if_exists='append',index=False)

以上參考檔案路徑:

https://blog.csdn.net/weixin_40683253/article/details/86741134