我有一个脚本,可以从 excel 文件中读取 500,000 行数据,然后插入到 MSSQL 数据库中;
如何减少插入时间?
我的代码如下:
cnxn = pyodbc.connect('DRIVER={SQL Server};Server=DESKTOP\MS2019;\
Database=203-Temp;Port=1433;User ID=sa;Password=1234;TrustServerCertificate=True')
cnxn.autocommit = False
cursor = cnxn.cursor()
data_df = pd.read_excel('a.xlsx').fillna(value=b'0')
data_dict = data_df.to_dict("records")
for row in tqdm(data_dict, desc="Inserting Data Into DataBase"):
c1= row['col1']
c2= row['col2']
c3= row['col3']
c4= row['col4']
c5= row['col5']
c6= row['col6']
c7= row['col7']
c8= row['col8']
c9= row['col9']
c10= row['col10']
cursor.execute(
"INSERT INTO Temp (UID, Name, ShName, GID, GLink,"
"GName,GAbout,PUID,PUnID,Date)"
" values (?,?,?,?,?,?,?,?,?,?)", c1, c2, c3, c4, c5, c6, c7, c8, c9, c10)
cursor.commit()
我使用方法 DataFrame.to_dict() 到常规数据。
我认为使用“BULK INSERT”或使用方法 curser.executemany() 可以帮助我。
你能给我什么?
如何使用这个方法?