預備知識1:從excel表中讀取數據,通過xlrd實現。
#打開工作表
ex = xlrd.open_workbook('d:\student.xlsx')
#操作工作表的sheet頁,第一頁
sheet = ex.sheet_by_index(0)
#獲取行數和列數
rows = sheet.nrows
cols = sheet.ncols
#獲取一行的數據
data = sheet.row_values('行號')
#獲取單元格的數據
data = sheet.cell('行號','列號').value
預備知識2:mysql數據庫操作
#數據庫連接 ,通過pymysql模塊
db = pymysql.connect(host='localhost',user='',password='',db='',port='')
#設置遊標,靠它進行數據庫操作
cursor = db.cursor()
#創建數據庫表格
create table 表名(字段,類型);
#向數據表中插入列
alter table 表名 add column 字段 類型;
#向表格中插入數據
insert into 表名(字段) values(數據)
準備工作完成後,就可以進行讀取數據,插入數據庫表格了。完整代碼如下:
import pymysql
import xlrd
def excel_to_sql():
excelf = xlrd.open_workbook(r'd:\student.xlsx')
sheet1 =excelf.sheet_by_index(0)
#取第一行表頭數據作爲插入創建表的字段
firstrow = sheet1.row_values(0)
sqlcol=','.join(firstrow) #用於後面插入數據
#取第二行的數據,爲插入字段的數據類型
secondrow = sheet1.row_values(1)
#取第第一列的第一行,第二行數據作爲創建表的初始值
firstdata = sheet1.cell(0,0).value #字段
firsttype = sheet1.cell(1,0).value #類型
#將excel表中存儲的類型對應到數據之中,string對應字符型
if firsttype == 'string':
firsttype = 'char(10)'
else:
firsttype = firsttype #int類型
cols = sheet1.ncols #總列數
rows = sheet1.nrows #總行數
#連接數據庫
db = pymysql.connect(host='localhost',user='test01',password='123456',db='testdb',port=3306)
#設置遊標,數據的操作就靠它了
cursor = db.cursor()
#創建STUDENT表,其中數據的字段和類型通過字符串格式化插入
sql = 'DROP TABLE IF EXISTS STUDENT;'
cursor.execute(sql)
sql = "CREATE TABLE STUDENT(%s %s);" % (firstdata,firsttype)
cursor.execute(sql)
#向STUDENT表中插入列,通過for循環從excel表中取出列的字段和類型
for i in range(1,cols):
colname = firstrow[i] #剩餘的字段
coltype = secondrow[i] #剩餘的字段類型
if coltype == 'string':
coltype = 'char(10)'
else:
coltype = coltype
sql = "ALTER TABLE STUDENT\
ADD COLUMN %s %s;" % \
(colname,coltype)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
#將數據插入已經創建好的表格中
for i in range(2,rows): #數據是從第三行開始的
student = sheet1.row_values(i)
for j in range(0,len(student)):
if isinstance(student[j],float):
student[j] = '%d' % student[j] #這裏攜程”‘%d’“這樣也可以,mysql裏面‘121’也能插入整型字段中
else:
student[j] = "'%s'" % student[j] #這裏一定要加一個引號,不然字符型不帶引號就不能插入數據庫
student1 = ','.join(student)#一次性取一行數據
sql = "INSERT INTO STUDENT(%s)\
values(%s);" %\
(sqlcol,student1) #這裏有一點值得注意的是mysql中int型的字段中,既可以插入12,也可以插入‘12’
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
excel_to_sql()
執行結果:
#student.xlsx