0

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...

0

3 Answers 3

1

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 (?,?,?,?,?,?);"
Sign up to request clarification or add additional context in comments.

Comments

1

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')-

Comments

0

as buran in the comment stated:

query = "INSERT INTO songs` {} VALUES (?,?,?,?,?,?);".format(header)

works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.