Python抓取Excel表数据至MySQL表

#encoding=utf-8
import xlrd
import MySQLdb

data=xlrd.open_workbook('test.xlsx')
table=data.sheets()[0]

nrows=table.nrows
ncols=table.ncols

tabledict={}

for i in range(nrows):
   tabledict[i]=table.row_values(i)
   
print tabledict[2]
print tuple(tabledict[2])


#读取数据
try:
   conn=MySQLdb.connect(host='localhost',user='root',passwd='1234',db='test',port=3306,charset='utf8')
   cur=conn.cursor()
   cur.execute('select Name, sex from classmate')
   result_set=cur.fetchall()
   for row in result_set:
      print row
   print "Number of rows returned: %d"%cur.rowcount
   cur.close()
   conn.close()
except MySQLdb.Error,e:
   print "MySQL Error %d:%s"%(e.args[0],e.args[1])
   
#插入数据
try:
   conn=MySQLdb.connect(host='localhost',user='root',passwd='1234',db='test',port=3306,charset='utf8')
   cur=conn.cursor()
   sql1="DROP table IF EXISTS ExcelTable;"
   cur.execute(sql1)
   print "Drop success!"
   sql2="create table IF NOT EXISTS ExcelTable(col1 varchar(20) primary key, col2 varchar(256),col3 int(10))"
   cur.execute(sql2)
   print "Sucess to create a new table!"
   
   #列表转元组,tabledict[i]
   
   #通过添加数据到列表中,然后再转为元组,因为元组是不可改的。
   sql3="insert into ExcelTable (col1,col2,col3) values(%s,%s,%s)"
   param01=[]
   for i in range(nrows):
      param01.append(tuple(tabledict[i]))
   param02=tuple(param01)
   print param02
   
   #多行数据
   try:
      cur.executemany(sql3,param02)
      conn.commit()
      print "success insert many records!"
   except Exception,e:
      conn.rollback()
      print e
   
   cur.close()
   conn.close()
except MySQLdb.Error,e:
   print "MySQL Error %d:%s"%(e.args[0],e.args[1])
 

具体的说明和细节,请看源码中的注释。

你可能感兴趣的:(sql,mysql,python,Excel,utf8)