Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2225166
  • 博文数量: 287
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2130
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-31 14:30
个人简介

自己慢慢积累。

文章分类

全部博文(287)

分类: Python/Ruby

2016-06-03 11:46:54

转自百度文库

如果数据量不大,直接用 Python 内部数据结构如 dict, list 就够了。但如果读取的几张表数据量都较大,增加个将数据插入数据库的预处理过程就有很大好处。一是避免每次调试都要进行耗时较长的 Excel 文件载入过程;二是能充分利用数据库的索引和 SQL 语句强大功能进行快速数据分析。

#!/usr/bin/python

# -*- coding: gbk -*-

import xlrd

import sqlite3

# 打开数据库文件

device_city_db = sqlite3.connect('device_city.db')

cursor = device_city_db.cursor()

# 建表

cursor.execute('DROP TABLE IF EXISTS device_city')

cursor.execute('CREATE TABLE device_city (device_id char(16) PRIMARY KEY, city varchar(16))')

 

# 打开 device 相关输入 Excel 文件

device_workbook = xlrd.open_workbook('输入.xlsx')

device_sheet = device_workbook.sheet_by_name('设备表')

# 逐行读取 device-城市 映射文件,并将指定的列插入数据库

for row in range(1, device_sheet.nrows):

   device_id = device_sheet.cell(row, 6).value

   if len(device_id) > 16:

       device_id = device_id[0:16]

   if len(device_id) == 0:

       continue

   city = device_sheet.cell(row, 10).value

   # 避免插入重复记录

   cursor.execute('SELECT * FROM device_city WHERE device_id=?', (device_id,))

   res = cursor.fetchone()

   if res == None:

       cursor.execute('INSERT INTO device_city (device_id, city) VALUES (?, ?)',

                      (device_id, city))

   else:

       if res[1] != city:

           print '%s, %s, %s, %s' % (device_id, city, res[0], res[1])

device_city_db.commit()

阅读(1327) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~