使用Excel初始化mysql資料庫

2021-10-06 03:09:51 字數 2361 閱讀 5139

# 讀取excel表的內容然後寫入資料庫

import xlrd,pymysql

# 資料庫配置

host =

'localhost'

# localhost:本地資料庫

user =

'root'

# 使用者名稱

password =

'123456'

# 密碼

database =

'test_database'

# 資料庫名稱

charset =

'utf8'

# 編碼方式

# 建立資料庫連線

conn = pymysql.connect(host=host, user=user, password=password

, database=database, charset=charset)

cursor = conn.cursor(cursor=pymysql.cursors.dictcursor)

excel_file =

"#i1fgq0資料庫.xlsx"

# 設定excel檔名

file

= xlrd.open_workbook(excel_file)

# 讀取excel檔案

sheets =

file

.sheet_names(

)#獲取所有的sheet頁

for sheet in sheets:

sheet_values =

file

.sheet_by_name(sheet)

# 獲取當前sheet頁內位址空間

sheet_rows = sheet_values.nrows # 獲取當前sheet行數

sheet_cols = sheet_values.ncols # 獲取當前sheet列數

# 因為sheet長度限制在31個字元,所以當sheet過長時,需要手動設定丟失部分

# sql字串拼接

sql =

"insert into "

+ sheet +

" ("

for i in

range(0

, sheet_cols)

:# 拼接字段

field_name =

str(sheet_values.cell(

0,i)

.value)

if(field_name ==

'desc'):

# 解決自定義欄位與sql關鍵字衝突

field_name =

'`desc`'

if(i ==

(sheet_cols-1)

):# 校驗是否到最後一列

sql += field_name +

") values ("

else

: sql += field_name +

","for j in

range(0

, sheet_cols)

:# 拼接佔位符

if(j ==

(sheet_cols-1)

):sql +=

"%s"

+")"

else

: sql +=

"%s"

+","

# 獲取每行value

for sheet_row in

range(1

, sheet_rows)

: values =

# 使用列表儲存

for sheet_col in

range(0

, sheet_cols)

: sheet_value =

str(sheet_values.cell(sheet_row,sheet_col)

.value)

# 當有些日期字段必填時,可以在這裡自定義if(

str(sheet_values.cell(

0,sheet_col)

.value)

=="add_time"):

sheet_value =

'2020-05-06'

ifnot sheet_value:

sheet_value =

none

values =

tuple

(values)

# 轉換成元組

cursor.execute(sql,values)

# 執行sql語句插入資料

conn.commit(

)cursor.close(

)conn.close(

)

mysql 初始化 MySQL初始化

port 3306 設定mysql的安裝目錄 basedir d php apmw mysql 8.0.17 設定mysql資料庫的資料的存放目錄 datadir d php apmw mysql 8.0.17 data 允許最大連線數 max connections 200 允許連線失敗的次數。m...

mysql 初始化序列 mysql初始化

mysqld nt remove mysql mysqld nt install mysqld initialize insecure user mysql mysqld install mysql root使用者拒絕連線 建立my.ini放在bin下 mysqld 設定3306埠 port 330...

mysql 初始化 mysql時間初始化

date forma t date,format 根據格式串format 格式化日期或日期和時間值date,返回結果串。可用date format 來格式化date 或datetime 值,以便得到所希望的格式。根據format字串格式化date值 s,s 兩位數字形式的秒 00,01,59 i 兩...