最近在做python相关的一些操作,在这里记录一下,以备忘记:
#coding=utf-8
import xlrd
import MySQLdb
book = xlrd.open_workbook("d://pythonTest/pytest.xlsx")
sheet = book.sheet_by_index(0)
#建立mysql连接
database = MySQLdb.connect(host='10.23.163.45',user='root',passwd='passwd',db='schedule_ad_v2',port=3306,use_unicode=True,charset="utf8")
# 获得游标对象, 用于逐行遍历数据库数据
cursor = database.cursor()
# 创建插入SQL语句
query = """
insert into operation_to_log_info (id,uri,operation_type,operation_name,manager) values(%s,%s,%s,%s,%s)
"""
# 转换字符串
def change(var):
if var == u'记录具体参数':
return 'detail'
if var == u'忽略':
return 'ignore'
else:
return 'visit'
def excel_insert_data():
i = 0
# 创建一个for循环迭代读取xls文件每行数据的, 从第二行开始是要跳过标题
for rx in range(1,sheet.nrows):
id = i
uri = sheet.cell(rx,1).value
operation_type = change(sheet.cell(rx,2).value)
operation_name = sheet.cell(rx,3).value
manager = sheet.cell(rx,4).value
values = (id,uri,operation_type,operation_name,manager)
cursor.execute(query,values)
i = i+1
def excel_close():
# 关闭游标
cursor.close()
# 提交
database.commit()
# 关闭数据库连接
database.close()
def main():
excel_insert_data()
excel_close()
print u"Done!恭喜"
if __name__ == "__main__":
main()