将所有数据从excell迁移到sqlite?

时间:2017-08-15 12:24:56

标签: python sqlite

我是python的新用户。我正在使用SQL。我想将数据从excel文件迁移到SQL。 这是我的代码:

import xlrd
import sqlite3

conn=sqlite3.connect("student.db")
crs=conn.cursor()

file_path="student.xlsx"

file=xlrd.open_workbook(file_path)
sheet=file.sheet_by_index(0)
data=[[sheet.cell_value(r,c)for c in range(sheet.ncols)] for r in range(sheet.nrows)]
for i in range(sheet.ncols):
    colm=data[0][i]
    crs.execute(("CREATE TABLE IF NOT EXISTS student([%s] VARCHAR(100))")%colm)

首先,我试图通过使用excel文件中的列来创建表,但我无法做到。之后,我想在列中插入每一行。可能,我在某个地方做错了,但我无法理解。

2 个答案:

答案 0 :(得分:0)

为什么不把整个表添加到sqlite数据库中?

conn = sqlite3.connect('student.db')
cur = conn.cursor()

file = pd.DataFrame("student.xlsx") #assuming your import this as a PD dataframe? You may want to include the path of the file if it is not in your working directory
'yourtablename'.to_sql("file", conn, if_exists="replace")

conn.commit()

' yourtablename'应该替换为您希望在数据库中为表提供的任何名称。然后,您可以使用以下代码验证您的表是否在数据库中

con = sqlite3.connect('student.db')
cur = con.cursor() 
cur.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;")
cur.fetchall()

答案 1 :(得分:0)

import xlrd
import sqlite3
import pandas as pd

conn = sqlite3.connect("student.db")
crs = conn.cursor()

file_path = "C:/Users/LANDGIS10/PycharmProjects/sqlite/student.xlsx"

file=xlrd.open_workbook(file_path)
sheet = file.sheet_by_index(0)
data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)]
df=pd.DataFrame(data)
df.to_sql("student1",conn,if_exists="replace")
conn.commit()
crs.fetchall()

但是,这不是我想要的,因为专栏中的列在sqlite中以行而不是table head进行迁移。这是结果。

"0" "ID"    "NO"    "NAME"  "SURNAME"
"1" "1.0"   "1234.0"    "Ali"   "ARSA"
"2" "2.0"   "23234.0"   "Mehmet"    "KOT"
"3" "3.0"   "234412.0"  "Adem"  "SAR"

我想要"ID" "NO" "NAME" "SURNAME"这个部分作为表头。