自己慢慢积累。
分类: Python/Ruby
2016-06-03 11:46:54
#!/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()