Shivams334
Shivams334

Reputation: 95

sql queries and python

I am trying use sqlite3 and python3 on the CSV file to extract the booking_id table for some specific data. But I am getting a KeyError which means the requested table is not in the dictionary. I don't get it.

import csv
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("CREATE TABLE t (booking_id,customer_id,source,status,checkin,checkout,oyo_rooms,hotel_id,amount,discount,date,PRIMARY KEY(booking_id))")
    with open('TableA.csv', 'r') as fin:
        dr = csv.DictReader(fin, delimiter='\t')
        to_db = [(i['booking_id'], i['customer_id'], i['source'], i['status'], i['checkin'], i['checkout'],
              i['oyo_rooms'], i['hotel_id'], i['amount'], i['discount'], i['date']) for i in dr]

        cur.executemany(
            "INSERT INTO t (booking_id,customer_id,source,status,checkin,checkout,oyo_rooms,hotel_id,amount,discount,date) VALUES (?, ?,?, ?, ?,?, ?,?, ?,?);", to_db)
        con.commit()
        con.close()

#error message 
KeyError: 'booking_id'

This is the csv file - https://pastebin.com/xbgFryhZ

Upvotes: 0

Views: 52

Answers (1)

nosklo
nosklo

Reputation: 222902

The key error you're getting means your csv file doesn't have that column. Post the first few lines from the csv file so we can check it out.

EDIT:

Now that you added the CSV file we can see that it is separated by commas, not tabs.

Change

dr = csv.DictReader(fin, delimiter='\t')

to

dr = csv.DictReader(fin, delimiter=',')

Upvotes: 2

Related Questions