The purpose of this script is to learn how to use lambda functions with map. I tried to insert a string to all columns of an sqlite TABEL and no error is shown yet the values didn't change.
def get_columns(self):
res=self.get_cursor().execute("SELECT * FROM EVENTS")
names = list(map(lambda x: x[0], res.description))
return names`
def update_to_last(self,column:str,data:str):
c=self.get_cursor()
print(column,data)
c.execute(f"UPDATE EVENTS SET '{column}'='{data}' WHERE ID ='(SELECT last_insert_rowid())'")
self.conn.commit()
if __name__ =="__main__":
d=DB()
columns=d.get_columns()
#this pile of map and lambda's ment to first get all of the columns names
#then add to every string a pair of some fictionary "data" to a list
#then the list is sent to update
map(lambda x:d.update_to_last(x[0],x[1]),(list(map(lambda column:[column,"data"],columns))))
CodePudding user response:
map
does not create a list of results. It produces items on demand as you iterate over the map
instance. You aren't iterating over the map
instance, so update_to_last
never gets called on anything.
Don't use map
for side effects. Use a regular for
loop.
# No need to turn the map instance into a list first; you
# can iterate over the map directly.
for x in map(lambda column: [column, "data"], columns):
d.update_to_last(x[0], x[1])
Of course, since "data"
is the fixed value of x[1]
, you really don't need map
at all.
for column in columns;
d.update_to_last(column, "data")
On the other hand, if d.update_to_last
produced an interesting return value that you wanted to store in a list, you might do somethign like
from itertools import repeat
x = list(map(d.list_to_update, columns, repeat("data")))
although a list comprehension like
x = [d.list_to_update(c, "data") for c in columns]
would be preferable.
CodePudding user response:
Did you mean something like this? (change the column name id
accordingly)
c.execute(f"UPDATE EVENTS SET '{column}'='{data}' WHERE id = (SELECT last_insert_rowid())")