I need to put the value "1" in the column, while the column name is stored in the variable "link_for_channel", so I do everything through a question mark. But I get a mistake.
Main code:
db.Add_StatusSubscription(link_for_channel=channels_URL[i])
At the moment, the link_for_channel variable stores a link "https:/t.me/insidertolk " and there is a column in the database called "https:/t.me/insidertolk ".
Database:
def Add_StatusSubscription(self, link_for_channel):
with self.conn:
return self.cursor.execute("INSERT INTO 'DataBase' (?) VALUES (1)", (link_for_channel,))
An error was coming out: OperationalError('near "?": syntax error')
I was told: Try using the F line or using %s
return self.cursor.execute(f"INSERT INTO 'DataBase' ({link_for_channel}) VALUES (1)")
#And
return self.cursor.execute("INSERT INTO 'DataBase' (%s) VALUES (1)" % link_for_channel)
But F string and %s give the same error: OperationalError('unrecognized token: ":"') Please help me!!
CodePudding user response:
You can't let the connector do substitution for table and column names. The substitution protects things with single quotes, which turns them into string literals.
You can protect special characters in table names with double quotes:
return self.cursor.execute(f'INSERT INTO DataBase ("{link_for_channel}") VALUES (1);')
However, I would argue that what you're doing is a bad practice. A URL is a piece of data, not a type of data. The URL should be in data column, not the title of a column. So the table should have two columns: 'url' and 'link'. Then, you do:
self.cursor.execute('INSERT INTO DataBase (url, link) VALUES (?,?)', (link_cur_channel, 1))