reduce variables
This commit is contained in:
parent
a527afeb80
commit
bb8800d47f
14
main.py
14
main.py
@ -44,23 +44,23 @@ class DBConn:
|
|||||||
print(f"create sql = {create_tbl_sql}")
|
print(f"create sql = {create_tbl_sql}")
|
||||||
self.cur.execute(create_tbl_sql)
|
self.cur.execute(create_tbl_sql)
|
||||||
|
|
||||||
def write_to_database(self, tbl, cols):
|
def write_to_database(self, tbl, column_data):
|
||||||
keys = cols.keys() # OrderedDict
|
col_names = column_data.keys() # OrderedDict
|
||||||
|
|
||||||
col_names = ', '.join(
|
col_names = ', '.join(
|
||||||
[f"\"{x}\"" for x in keys]
|
[f"\"{x}\"" for x in col_names]
|
||||||
)
|
)
|
||||||
value_placeholders = ', '.join(
|
value_placeholders = ', '.join(
|
||||||
["?" for _ in keys]
|
["?" for _ in col_names]
|
||||||
)
|
)
|
||||||
# trim values of spaces
|
# trim values of spaces
|
||||||
values = tuple([str(cols[k]).strip() for k in keys])
|
values = tuple([str(column_data[k]).strip() for k in col_names])
|
||||||
|
|
||||||
# there might be a scenario that new cols might appear at a later stage, if so,
|
# there might be a scenario that new cols might appear at a later stage, if so,
|
||||||
# we shall accommodate by adding it to the database
|
# we shall accommodate by adding it to the database
|
||||||
tbl_cols = self.table_mapping[tbl]
|
tbl_cols = self.table_mapping[tbl]
|
||||||
not_found = []
|
not_found = []
|
||||||
for col in cols:
|
for col in col_names:
|
||||||
if col not in tbl_cols:
|
if col not in tbl_cols:
|
||||||
not_found.append(col)
|
not_found.append(col)
|
||||||
|
|
||||||
@ -69,7 +69,7 @@ class DBConn:
|
|||||||
self.cur.execute(f"alter table \"{tbl}\" add column \"{new_col}\" text")
|
self.cur.execute(f"alter table \"{tbl}\" add column \"{new_col}\" text")
|
||||||
|
|
||||||
print(f"added {not_found} cols to {tbl}")
|
print(f"added {not_found} cols to {tbl}")
|
||||||
self.table_mapping[tbl] = cols
|
self.table_mapping[tbl] = column_data
|
||||||
|
|
||||||
sql = f"insert into \"{tbl}\" ({col_names}) values({value_placeholders})"
|
sql = f"insert into \"{tbl}\" ({col_names}) values({value_placeholders})"
|
||||||
self.cur.execute(sql, values)
|
self.cur.execute(sql, values)
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user