利用Python將Excel的資料更新進MySQL

2021-09-14 03:41:03 字數 3438 閱讀 1941

我們在實際工作中,可能會遇到需要定期批量更新資料庫中某個欄位的值,比如學生花名冊的【曾用名】就需要定期更新(只更新這個字段,其餘的資料不需要改變)。但是現有的資料庫管理工具沒有這種批量更新部分欄位的功能,基本只有追加、清空再插入、新建表等功能。

需求描述:比如現在我手裡已經有張excel表,裡面就2列,一列是學號,一列是曾用名。我要把【曾用名】按照學號更新進mysql的學生花名冊。

這個功能利用**來實現,邏輯很簡單,就是如下語句的乙個迴圈:

update table1 set 欄位1

=值1,

set 欄位2

=值2,

set 欄位2

=值2where 條件;

通過這樣乙個簡單例子,我把這種需求抽象出來,定義了乙個方法update_xiangmu

使用方法是:

update_xiangmu(

mysql資料庫連線引數,

需要更新的表名,

excel路徑,

需要更新的字段資料來自excel中的第幾張表,

需要更新的字段[字典形式],

匹配的字段[字典形式]

)

import pymysql  #pymysql不是anaconda自帶的,需要安裝。

import xlrd

import datetime

import math

defupdate_xiangmu

(dbconfig,table,xlpath,shtnum,cols_upd,col_on)

:#連線資料庫的引數放在乙個字典裡,需要更新的表名,excel路徑,第幾張表,需要更新的字段列表(字典形式,欄位名:第幾列),作為匹配的字段(字典形式,匹配欄位名:第幾列。支援復合索引)

#這裡面引數的第幾,都是從1開始數。不用管是從0還是從1,因為下文會處理

#預設專案中心、專案、專案細分、專案課程是挨著的。

#大概2秒更新1000行

#excel路徑含中文好像不會報錯。

db = pymysql.connect(

**dbconfig)

#解開字典引數

print

(str

(datetime.datetime.now())

+'連線mysql資料庫成功,正在開始讀取excel...'

) readbook=xlrd.open_workbook(xlpath)

sheet = readbook.sheet_by_index(shtnum-1)

#索引的方式,從0開始,所以要減1

print

(xlpath+

' 的最大有效行數是:'

+str

(sheet.nrows)

)print

(xlpath+

' 的最大有效列數是:'

+str

(sheet.ncols)

) cursor = db.cursor(

)try

: i =

1 starttime = datetime.datetime.now(

)# 現在

print(+

str(starttime)

)while i <= sheet.nrows-1:

list_upd =

#需要更新的字段

for key, value in cols_upd.items():

" %s = '%s'"

%(key,

str(sheet.cell(i, value -1)

.value)))

#單元格位置下標是從0開始的,和vba不同。而且是cell 而非cells

str_upd =

','.join(list_upd)

# 生成文字,如: 專案中心='高中',專案='語文'

list_on =

#作為匹配的字段

for key,value in col_on.items():

" %s = '%s'"

%(key,

str(sheet.cell(i, value -1)

.value)))

str_on =

' and '

.join(list_on)

#where 後面的句子用and 連線。多數情況不會出現and

# 本質就是這個句子的迴圈: update table set 欄位1=值1,欄位2=值2 where 欄位a=欄位b and...

strsql =

"update %s set %s where %s "

%(table, str_upd, str_on)

cursor.execute(strsql)

if i%

1000==0

:#每隔千行重新整理下

p1=math.ceil(

100*i/

(sheet.nrows-1)

)#進度

print

('\r'

,'#'

*(p1)

+str

(p1)

+'% 已載入'

+str

(i)+

'行', end=

'', flush=

true

)#進度條

i +=

1 db.commit(

)# 預設需要主動提交

print

('\n'

+'successfully finished within :'

+str

(datetime.datetime.now(

)- starttime)

)except exception as e:

# 如果發生錯誤則回滾

db.rollback(

)print

(e)print

('sql語句:'

+strsql)

print

('執行不成功,已回滾'

)finally

:# 關閉資料庫連線

cursor.close(

) db.close(

)if __name__ ==

'__main__'

:#舉個例子

config =

update_xiangmu(dbconfig=config,table=

'class'

, xlpath=r'c:\users\administrator\desktop\測試\mysql測試\data.xlsx'

, shtnum=

1,cols_upd=

,col_on=

)#cols_upd和col_on 字典裡可以寫多個字段,格式是:

這是我寫的第乙個部落格,歡迎指正。

2019-03-30

如何利用pandas將Excel轉為html格式

大家談及用pandas匯出資料,應該就會想到to.系列的函式。這其中呢,比較常用的就是pd.to csv 和pd.to exupoqrtvtocel 但其實還可以將其導成html網頁格式,這裡用到的函式就是pd.to html 今天我們要實現excel轉為html格式,首先需要用讀取excel中的 ...

利用Python處理Excel資料

資料清洗 資料預處理 資料提取 資料篩選 資料彙總 資料統計 import pandas as pd import numpy as np import matplotlib.pyplot as plt from datetime import datetime from pandas import...

利用Python處理Excel資料

目錄 資料清洗 資料預處理 資料提取 資料篩選 資料彙總 資料統計 import pandas as pd import numpy as np import matplotlib.pyplot as plt from datetime import datetime from pandas imp...