码迷,mamicode.com
首页 > 数据库 > 详细

python读取excel数据插入sqlite中

时间:2020-05-12 11:27:14      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:text   存在   数据   sqli   pre   xls   mit   book   读取   

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Hogan


import xlrd
import sqlite3


def read_excel(fileName):
# 打开文件excel
workBook = xlrd.open_workbook(fileName)

# 打开表格
table = workBook.sheets()[0]
# 计算文档有多少行
all_row = table.nrows

# 返回打开文档的对象,和文档的总行数
return table, all_row


def create_con(dbname):
# conn = sqlite3.connect(‘example2.db‘) # 连接数据库
conn = sqlite3.connect(dbname) # 连接数据库
# connect()方法,可以判断一个数据库文件是否存在,如果不存在就自动创建一个,如果存在的话,就打开那个数据库。
cus = conn.cursor() # 创建游标
return cus, conn


def sql_dao(da, cus):
# cus.execute(‘‘‘CREATE TABLE stocks(id real ,lng REAL ,lat REAL,slp REAL ,intensity real ,utc text )‘‘‘)

# 向表中插入一条数据
sql = ‘‘‘insert into stocks values(%s,‘%s‘,‘%s‘,‘%s‘,‘%s‘,‘%s‘)‘‘‘ % (da[0], da[1], da[2], da[3], da[4], da[5])
cus.execute(sql)


def submit_close(conn):
# 提交当前事务,保存数据
conn.commit()
# 关闭数据库连接
conn.close()


if __name__ == ‘__main__‘:
row_all_obj, all_row_num = read_excel("datastr.xlsx")
conn, cus = create_con()
for i in range(1, all_row_num + 1):
data = row_all_obj.row_values(i)
sql_dao(data,cus )
print("插入第", i, "条")
submit_close(conn)

python读取excel数据插入sqlite中

标签:text   存在   数据   sqli   pre   xls   mit   book   读取   

原文地址:https://www.cnblogs.com/hoganhome/p/12874614.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!