python excel to mysql
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的更多相关文章
- python2.7爬取豆瓣电影top250并写入到TXT,Excel,MySQL数据库
python2.7爬取豆瓣电影top250并分别写入到TXT,Excel,MySQL数据库 1.任务 爬取豆瓣电影top250 以txt文件保存 以Excel文档保存 将数据录入数据库 2.分析 电影 ...
- xlrd(excel导入mysql数据库)
一.xlrd模块: python 对 excel 文件进行读操作 1.下载xlrd 并安装 http://pypi.python.org/pypi/xlrd wget https://pypi.pyt ...
- python3爬取”理财大视野”中的股票,并分别写入txt、excel和mysql
需求:爬取“理财大视野”网站的排名.代码.名称.市净率.市盈率等信息,并分别写入txt.excel和mysql 环境:python3.6.5 网站:http://www.dashiyetouzi.co ...
- 实战|教你用Python玩转Mysql
爬虫采集下来的数据除了存储在文本文件.excel之外,还可以存储在数据集,如:Mysql,redis,mongodb等,今天辰哥就来教大家如何使用Python连接Mysql,并结合爬虫为大家讲解. 前 ...
- Python中操作mysql的pymysql模块详解
Python中操作mysql的pymysql模块详解 前言 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而后者不支持 ...
- Python excel 库:Openpyxl xlrd 对比 介绍
打算用python做一个写mtk camera driver的自动化工具. 模板选用标准库里面string -> Template 即可 但要重定义替换字符,稍后说明 配置文件纠结几天:cfg, ...
- python——django使用mysql数据库(二)
上一篇中,我们已经讲述了如何初始化一个django数据库,这一章就来讲讲在实际的项目中如何使用我们初始化的数据库呢? 如还未进行初始化数据库操作,请参考python——django使用mysql数据库 ...
- python——django使用mysql数据库(一)
之前已经写过如何创建一个django项目,现在我们已经有了一个小骷髅,要想这个web工程变成一个有血有肉的人,我们还需要做很多操作.现在就先来介绍如何在django中使用mysql数据库. 前提:已经 ...
- Python 3 and MySQL
http://stackoverflow.com/questions/4960048/python-3-and-mysql up vote61down votefavorite 20 I am usi ...
随机推荐
- spark通过JDBC读取外部数据库,过滤数据
官网链接: http://spark.apache.org/docs/latest/sql-programming-guide.html#jdbc-to-other-databases http:// ...
- (四十五)c#Winform自定义控件-水波图表
前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. GitHub:https://github.com/kwwwvagaa/NetWinformControl 码云:ht ...
- 从零开始实现ASP.NET Core MVC的插件式开发(五) - 插件的删除和升级
标题:从零开始实现ASP.NET Core MVC的插件式开发(五) - 使用AssemblyLoadContext实现插件的升级和删除 作者:Lamond Lu 地址:https://www.cnb ...
- nginx对特定参数限流
接到一个需求, 需要对请求(GET)里面的某个参数 的特定的值, 进行限流; 因为不限流的话, 不知道什么时候这个id的请求飙一下, 服务端就被压死了... 就像这样: /index.html?id ...
- Nacos(六):多环境下如何“管理”及“隔离”配置和服务
前言 前景回顾: Nacos(五):多环境下如何"读取"Nacos中相应环境的配置 Nacos(四):SpringCloud项目中接入Nacos作为配置中心 现如今,在微服务体系中 ...
- [Python] 数据结构--实现顺序表、链表、栈和队列
说明: 本文主要展示Python实现的几种常用数据结构:顺序表.链表.栈和队列. 附有实现代码. 来源主要参考网络文章. 一.顺序表 1.顺序表的结构 一个顺序表的完整信息包括两部分,一部分是表中元素 ...
- 2019-04-23-Python爬取有声小说
目录 Python爬取有声小说 摘要 1.获取下载链接 2.分析规律,循环爬取 3.保存到本地,批量命名 4.界面设计 5.效果展示 Python爬取有声小说 通过python爬取网站的资源,实现批量 ...
- Servlet,过滤器和监听器的配置和使用
一.什么是Servlet Servlet使用Java语言实现的程序,运行于支持Java语言的Web服务器或者应用服务器中.Servlet先于JSP出现,提供和客户端动态交互的功能.Servlet可以处 ...
- HZNU 2019 Summer training 6 -CodeForces - 622
A - Infinite Sequence CodeForces - 622A 题目大意:给你一个这样的数列1,1,2,1,2,3,1,2,3,4,1,2,3,4,5....就是从1~n排列(n++ ...
- codeforces 284 C. Cows and Sequence(线段树)
题目链接:http://codeforces.com/contest/284/problem/C 题意:就是给出3个操作 1)是将前i 个数加x 2)在数组最后添加一个数x 3)删除数组最后的那个数 ...