I am struggling to use ON DUPLICATE KEY with my current code:
def upload_to_database(ticker_collection):
trend_data = []
trend_data_table = "trend_data"
trend_data_columns = "Ticker, Subreddit, Score, Rockets, Date"
trend_data_sql = "INSERT INTO " + trend_data_table +\
" (" + trend_data_columns + ") VALUES (%s, %s, %s, %s, %s) " +\
"ON DUPLICATE KEY UPDATE " +\
"Score = Score + %s, " +\
"Rockets = Rockets + %s"
for ticker in ticker_collection:
ticker_subreddit = ticker_collection[ticker]['subreddit']
ticker_score = int(ticker_collection[ticker]['score'])
ticker_rockets = int(ticker_collection[ticker]['rockets'])
insert_date = datetime.date(datetime.now(est))
ticker_data = (ticker, ticker_subreddit, ticker_score, ticker_rockets, insert_date, 1, 1)
trend_data.append(ticker_data)
the_db_cursor.executemany(trend_data_sql, trend_data)
the_database.commit()
return the_db_cursor.rowcount, "was inserted."
trend_data_sql is my query and towards the end there is Score and Rockets, effectively if an entry with the same Ticker and DateTime (my unique keys) exists I only want to update the score and rockets for that entry.
However, I am trying to do this with executemany() to save on db performance. I am a little stuck on how to incorporate ON DUPLICATE KEY with the for loop and executemany().
Any guidance or advice would be much appreciated.
Table Structure:
CREATE TABLE `trend_data` (
`Ticker` varchar(255) NOT NULL,
`Subreddit` varchar(255) NOT NULL,
`Score` int(11) NOT NULL,
`Rockets` int(11) NOT NULL,
`Date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Table Indexes:
ALTER TABLE `trend_data`
ADD UNIQUE KEY `Unique_Keys` (`Ticker`,`Date`,`Subreddit`) USING BTREE;