简体   繁体   中英

sqlite3 INSERT INTO query in python, string format

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

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 (?,?,?,?,?,?);"

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

as buran in the comment stated:

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

works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM