python 读取sqlite存入文件_如何使用python从csv文件读取数据并在sqlite3中存储数据...

这篇博客介绍了一个Python类readCSVintoDB,该类用于从CSV文件中读取特定字段并存储到SQLite3数据库中。作者遇到了`IntegrityError: datatype mismatch`的错误,这可能是由于尝试插入的数据类型与数据库表结构不符。代码中展示了创建数据库、定义表结构以及尝试插入数据的过程。
摘要由CSDN通过智能技术生成

我有一个python类readCSVintoDB,它从csv文件中读取数据并将数据存储到sqlite 3数据库中。在

注:

csv文件包括许多字段,所以我只需要其中的3个。在

到目前为止,我能够读取csv文件,并使用pandas将其存储到数据帧中。但是如何将数据帧存储到数据库中。在

显示的错误:File "C:\Users\test\Documents\Python_Projects\readCSV_DB.py", line 15,

in init self.importCSVintoDB() File

"C:\Users\test\Documents\Python_Projects\readCSV_DB.py", line 60, in

importCSVintoDB INSERT INTO rduWeather VALUES (?,?,?,?)''', i)

sqlite3.IntegrityError: datatype mismatch

当我试图在for循环中打印i时,它会显示标题名称日期

readCSV_数据库:import sqlite3

import pandas as pd

import os

class readCSVintoDB():

def __init__(self):

'''

self.csvobj = csvOBJ

self.dbobj = dbOBJ

'''

self.importCSVintoDB()

def importCSVintoDB(self):

userInput= input("enter the path of the csv file: ")

csvfile = userInput

df = pd.read_csv(csvfile,sep=';')

#print("dataFrame Headers is {0}".format(df.columns))# display the Headers

dp = (df[['date','temperaturemin','temperaturemax']])

print(dp)

'''

check if DB file exist

if no create an empty db file

'''

if not(os.path.exists('./rduDB.db')):

open('./rduDB.db','w').close()

'''

connect to the DB and get a connection cursor

'''

myConn = sqlite3.connect('./rduDB.db')

dbCursor = myConn.cursor()

'''

Assuming i need to create a table of (Name,FamilyName,age,work)

'''

dbCreateTable = '''CREATE TABLE IF NOT EXISTS rduWeather

(id INTEGER PRIMARY KEY,

Date varchar(256),

TemperatureMin FLOAT,

TemperatureMax FLOAT)'''

dbCursor.execute(dbCreateTable)

myConn.commit()

'''

insert data into the database

'''

for i in dp:

print(i)

dbCursor.execute('''

INSERT INTO rduWeather VALUES (?,?,?,?)''', i)

#myInsert=dbCursor.execute('''insert into Info ('Name','FA','age','work')

#VALUES('georges','hateh',23,'None')''')

myConn.commit()

mySelect=dbCursor.execute('''SELECT * from rduWeather WHERE (id = 10)''')

print(list(mySelect))

myConn.close()

test1 = readCSVintoDB()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值