· 8 years ago · Feb 18, 2018, 09:12 PM
1import sqlite3 as lite
2
3
4def create_database(database_path: str):
5 conn = lite.connect(database_path)
6 with conn:
7 cur = conn.cursor()
8 cur.execute("drop table if exists words")
9 ddl = "create table words (word TEXT not null primary key, usage_count INT default 1 not null)";
10 cur.execute(ddl)
11 ddl = "create unique index table_name_word_uindex on words (word)";
12 cur.execute(ddl)
13 conn.close()
14
15def save_words_to_database(database_path: str, words_list: list):
16 conn = lite.connect(database_path)
17 with conn:
18 cur = conn.cursor()
19 for word in words_list:
20 # check to see if the word is in there
21 sql = "select count(word) from words where word ='" + word + "'"
22 cur.execute(sql)
23 count = cur.fetchone()[0]
24 if count > 0:
25 sql = "update words set usage_count = usage_count + 1 where word = '" + word + "'"
26 else:
27 sql = "insert into words(word) values ('" + word + "')"
28 cur.execute(sql)
29 # conn.close() I had a repeating error here due to the print command being listed in the loop above.
30
31print("Database Operations (save) Complete!")