python 3.7,vscode
這有效:
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()
這個:
def insert_song(cursor):
header = get_header(cursor)
query = "INSERT INTO `songs` ({}) VALUES (?,?,?,?,?,?);".format(header)
cursor.execute(query, get_info(cursor))
connection.commit()
產生以下錯誤:
sqlite3.OperationalError: near "(": syntax error
“get_header(cursor)”函式的回傳遵循元組:
('song', 'album', 'artist', 'genre', 'duration', 'price')
正如我所暗示的,這是 .format 的一個問題,我必須定義一些額外的東西,但我沒有找到它......
uj5u.com熱心網友回復:
當你傳遞元組時,你也會得到括號,所以你的查詢中會有雙括號
嘗試
query = "INSERT INTO `songs` {} VALUES (?,?,?,?,?,?);".format(header)
甚至更好地使用 f-string
query = f"INSERT INTO `songs` {header} VALUES (?,?,?,?,?,?);"
或直接
query = f"INSERT INTO `songs` {get_header()} VALUES (?,?,?,?,?,?);"
uj5u.com熱心網友回復:
我認為問題的格式來自格式字串。它將有雙 () 因為標題的格式將包括 header () :
header=('a','b')
query="-({})-".format(header)
print(query)
這將列印:
-(('a', 'b'))-
如果你從格式中抑制 (),你想要什么:
query2="-{}-".format(header)
print(query2)
列印出來:
-('a', 'b')-
uj5u.com熱心網友回復:
正如buran在評論中所說:
query = "INSERT INTO songs` {} VALUES (?,?,?,?,?,?);".format(header)
作品
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/328806.html
