python 3.7, vscode
This works:
def insert_song(cursor):
header = get_header(cursor)
query = "INSERT INTO `songs` ('song', 'album', 'artist', 'genre', 'duration', 'price') VALUES (?,?,?,?,?,?);"
cursor.execute(query, get_info(cursor))
connection.commit()
This:
def insert_song(cursor):
header = get_header(cursor)
query = "INSERT INTO `songs` ({}) VALUES (?,?,?,?,?,?);".format(header)
cursor.execute(query, get_info(cursor))
connection.commit()
generates following error:
sqlite3.OperationalError: near "(": syntax error
the return of the "get_header(cursor)" function is following tuple:
('song', 'album', 'artist', 'genre', 'duration', 'price')
as i get hinted, it's a problem with .format which i have to define something additional but i didn't find it...
CodePudding user response:
When you pass tuple, you get also the brackets, so you will have double brackets in your query
Try
query = "INSERT INTO `songs` {} VALUES (?,?,?,?,?,?);".format(header)
or even better using f-string
query = f"INSERT INTO `songs` {header} VALUES (?,?,?,?,?,?);"
or directly
query = f"INSERT INTO `songs` {get_header()} VALUES (?,?,?,?,?,?);"
CodePudding user response:
I think the format of the problem comes from the format string . It will have double () because formatting of header will include header () :
header=('a','b')
query="-({})-".format(header)
print(query)
This will print :
-(('a', 'b'))-
If you suppress the () from the format, you gay what you want :
query2="-{}-".format(header)
print(query2)
Prints out :
-('a', 'b')-
CodePudding user response:
as buran in the comment stated:
query = "INSERT INTO songs` {} VALUES (?,?,?,?,?,?);".format(header)
works