import sys
import xlrd
import pymysql
import math
import json
from collections import OrderedDict # json 转换成对像
class JSONObject:
def __init__(self, d):
self.__dict__ = d # 异常处理
class MyError(Exception):
def __init__(self, v):
self.value = v def __str__(self):
return repr(self.value) # 读取数据
config = None with open('config.json', 'r') as f:
try:
config = json.load(f, object_pairs_hook=OrderedDict)
except IOError as err:
print("OS error: {0}".format(err))
sys.stdin.readline()
finally:
if sys.exc_info()[0] is not None:
print("else Unexpected error:", sys.exc_info())
sys.stdin.readline()
# raise MyError('else Unexpected error') fileList = []
# print(config)
for k in config:
if k == 'fileList':
for d in config[k]:
if config[k][d] == 1:
fileList.append(d) # 建立mysql连接
conn = pymysql.connect(
host=config['host'],
user=config['user'],
passwd=config['passwd'],
db=config['db'],
port=config['port'],
charset=config['charset']
) # 获得游标
cur = conn.cursor() for filename in fileList:
cur.execute('delete from ' + filename);
print(filename + ' 删除数据!')
book = xlrd.open_workbook('excel/' + filename + '.xlsx')
sheet = book.sheets()[0]
ops = []
nCols = sheet.ncols # 获取列表的有效列数
colName = 'insert into ' + filename
first = 0
flag = ','
# 表中的数据有单引号,直接拼接处理
if filename == 'tbl':
names = []
for r in range(0, sheet.nrows):
if first != 0:
flag = '^'
values = ''
itemSql = colName
for col in range(0, nCols):
value = sheet.cell(r, col).value
if isinstance(value, int):
values += str(math.floor(value)) + flag
elif isinstance(value, float):
values += str(math.floor(value)) + flag
else:
values += value + flag values = values[0:-1] # 第0行为字段行
if first == 0:
colName += '(' + values + ')' + ' values ('
else:
for d in values.split(flag):
itemSql += '"' + d + '",'
itemSql = itemSql[0:-1]
itemSql += ');'
# print(itemSql)
try:
cur.execute(itemSql)
except IOError as err:
print("OS error: {0}".format(err))
sys.stdin.readline()
finally:
if sys.exc_info()[0] is not None:
print("finally Unexpected error:", sys.exc_info())
sys.stdin.readline() first = 1 print(filename + ' 导入新数据!')
else:
for r in range(0, sheet.nrows):
if first != 0:
flag = '&'
values = ''
for col in range(0, nCols):
value = sheet.cell(r, col).value
if isinstance(value, int):
values += str(math.floor(value)) + flag
elif isinstance(value, float):
values += str(math.floor(value)) + flag
else:
values += value + flag values = values[0:-1] if first == 0:
colName += '(' + values + ')' + ' values ('
for j in range(0, nCols):
if j == nCols - 1:
colName += '%s)'
else:
colName += '%s, '
else:
ops.append(values.split(flag)) first = 1 # print(colName)
# print(ops)
try:
cur.executemany(colName, ops)
print(filename + ' 导入新数据!')
except IOError as err:
print("OS error: {0}".format(err))
sys.stdin.readline()
finally:
if sys.exc_info()[0] is not None:
print("finally Unexpected error:", sys.exc_info())
sys.stdin.readline() cur.close()
conn.commit()
conn.close() print('导入完成, 按任意键关闭...')
sys.stdin.readline()

python excel to mysql的更多相关文章

  1. python2.7爬取豆瓣电影top250并写入到TXT,Excel,MySQL数据库

    python2.7爬取豆瓣电影top250并分别写入到TXT,Excel,MySQL数据库 1.任务 爬取豆瓣电影top250 以txt文件保存 以Excel文档保存 将数据录入数据库 2.分析 电影 ...

  2. xlrd(excel导入mysql数据库)

    一.xlrd模块: python 对 excel 文件进行读操作 1.下载xlrd 并安装 http://pypi.python.org/pypi/xlrd wget https://pypi.pyt ...

  3. python3爬取”理财大视野”中的股票,并分别写入txt、excel和mysql

    需求:爬取“理财大视野”网站的排名.代码.名称.市净率.市盈率等信息,并分别写入txt.excel和mysql 环境:python3.6.5 网站:http://www.dashiyetouzi.co ...

  4. 实战|教你用Python玩转Mysql

    爬虫采集下来的数据除了存储在文本文件.excel之外,还可以存储在数据集,如:Mysql,redis,mongodb等,今天辰哥就来教大家如何使用Python连接Mysql,并结合爬虫为大家讲解. 前 ...

  5. Python中操作mysql的pymysql模块详解

    Python中操作mysql的pymysql模块详解 前言 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而后者不支持 ...

  6. Python excel 库:Openpyxl xlrd 对比 介绍

    打算用python做一个写mtk camera driver的自动化工具. 模板选用标准库里面string -> Template 即可 但要重定义替换字符,稍后说明 配置文件纠结几天:cfg, ...

  7. python——django使用mysql数据库(二)

    上一篇中,我们已经讲述了如何初始化一个django数据库,这一章就来讲讲在实际的项目中如何使用我们初始化的数据库呢? 如还未进行初始化数据库操作,请参考python——django使用mysql数据库 ...

  8. python——django使用mysql数据库(一)

    之前已经写过如何创建一个django项目,现在我们已经有了一个小骷髅,要想这个web工程变成一个有血有肉的人,我们还需要做很多操作.现在就先来介绍如何在django中使用mysql数据库. 前提:已经 ...

  9. Python 3 and MySQL

    http://stackoverflow.com/questions/4960048/python-3-and-mysql up vote61down votefavorite 20 I am usi ...

随机推荐

  1. Django Mysql数据库-基于双下划线的跨表查询

    一.基于双下划线的跨表查询 Django 还提供了一种直观而高效的方式在查询(lookups)中表示关联关系,它能自动确认 SQL JOIN 联系.要做跨关系查询,就使用两个下划线来链接模型(mode ...

  2. Java虚拟机详解(六)------内存分配

    我们说Java是自动进行内存管理的,所谓自动化就是,不需要程序员操心,Java会自动进行内存分配和内存回收这两方面. 前面我们介绍过如何通过垃圾回收器来回收内存,那么本篇博客我们来聊聊如何进行分配内存 ...

  3. 委托和lambda表达式,Action和Func

    1.为什么要用委托 我们为什么要有委托?任何东西存在即合理,不合理的也会被时间淘汰掉,委托既然存在肯定有存在的必要,我们来看一下什么时候可以用到委托. 接下来我们有个需求,就是调用一个方法,取出1-1 ...

  4. SparkSQL Adaptive Execution

    转自 https://mp.weixin.qq.com/s/Oq9L3Cmc-8G9oL8dvZ5OHQ 1 背景 本文介绍的 Adaptive Execution 将可以根据执行过程中的中间数据优化 ...

  5. CSS动效集锦,视觉魔法的碰撞与融合(一)

    前言 在本文中我讲述了7种CSS的动效,它们也许看起来并不惊艳,但是我认为却足够传达本文的理念:编写一些特殊的CSS样式的时候需要不拘于常理,要用特殊的认识角度看待标签和样式属性,从而用「绕个弯」的方 ...

  6. MySQL里的COUNT

    count(*).count(1).count(主键).count(字段)的执行效率 在没有where条件的情况下 MyISAM引擎返回结果会比InnoDB快上很多,主要是因为MyISAM会单独记录了 ...

  7. vue-cli报错:Class constructor FileManager cannot be invoked without 'new'

    bug:vue-cli3开发的项目,今天项目重新下载依赖启动项目的时候出现错误:Class constructor FileManager cannot be invoked without 'new ...

  8. Redis学习总结(六)--Redis集群伸缩

    我们在上一章讲了如何创建集群,今天我们来实现下集群的伸缩. 添加节点 操作流程 1.启动节点 2.将节点加入到集群中 3.将数据槽从原来的节点迁移部分到新节点上 实践 1)准备两个新节点并启动 [ro ...

  9. 从入门到实践:创作一个自己的 Helm Chart

    前言 我们平时在日常生活中会经常在不同的平台上与各种各样的应用打交道,比如从苹果的 App Store 里下载的淘宝.高德.支付宝等应用,或者是在 PC 端安装的 Word.Photoshop.Ste ...

  10. Leetcode之二分法专题-852. 山脉数组的峰顶索引(Peak Index in a Mountain Array)

    Leetcode之二分法专题-852. 山脉数组的峰顶索引(Peak Index in a Mountain Array) 我们把符合下列属性的数组 A 称作山脉: A.length >= 3 ...