I am working on a python application in which I connect to the existing SQLite database and table. I have a CSV file containing one value per row (stocks symbol) and I want to import all the values into the existing table column "symbol" using python. How can I do this?
What I've tried is defining an insert function:
def insert(symbol):
conn=sqlite3.connect("stocks.db")
cur=conn.cursor()
cur.executemany("INSERT INTO stocks (symbol) VALUES (?)", (symbol,))
conn.commit()
conn.close()
and then try looping in the value and adding the values from there:
with open("./stocks/sp500_tickers.csv") as data:
tickers = data.read()
for ticker in tickers:
insert(ticker)
But when I run the python code, I get this error:
Traceback (most recent call last):
File "fetch.py", line 64, in <module>
insert(ticker)
File "fetch.py", line 23, in insert
cur.execute("INSERT INTO stocks (symbol) VALUES (?)", (symbol,))
sqlite3.IntegrityError: UNIQUE constraint failed: stocks.symbol
The same thing happens if I try like this:
with open("./stocks/sp500_tickers.csv") as data:
tickers = data.read()
rows = tickers.split('\n')
formatted = [tuple(x.split()) for x in rows]
for ticker in tickers:
insert(ticker)
The schema for the table is:
id INTEGER NOT NULL,
symbol VARCHAR,
name VARCHAR,
price NUMERIC(10, 2),
book_value NUMERIC(10, 2),
trailing_pe NUMERIC(10, 2),
forward_pe NUMERIC(10, 2),
trailing_eps NUMERIC(10, 2),
forward_eps NUMERIC(10, 2),
dividend_yield NUMERIC(10, 2),
ma50 NUMERIC(10, 2),
ma200 NUMERIC(10, 2),
sector VARCHAR,
growth_rate NUMERIC(10, 2),
PRIMARY KEY (id)
);
CREATE INDEX ix_stocks_id ON stocks (id);
CREATE UNIQUE INDEX ix_stocks_symbol ON stocks (symbol);
My "sp500_tickers.csv" looks something like this:
MMM
ABT
ABBV
ABMD
etc
Any help is very welcomed!
insertfails, useupdate. For that you will have to perform individual transactions not a batch ttransaction.print()command to debug stuff like this i.e.print("inserting", symbol). It pays to know what you are asking the code to do.