0

您好我在尝试添加时间戳时遇到错误。我不断收到错误asyncpg.exceptions.PostgresSyntaxError: syntax error at or near "18",这条线end_date = duration + dt.datetime.now(bst) # timestamp似乎是罪魁祸首,但我不确定为什么会这样。

这是我正在使用的内容:

    if time is not None:
        conn = await asyncpg.connect(DATABASE_URL)
        async with conn.transaction():
            await conn.fetch(f"SELECT time FROM blacklist WHERE username={member.id}")
        
            duration = find_date(time)
            bst = pytz.timezone('Europe/London')
            end_date = duration + dt.datetime.now(bst) # timestamp
            fmt_date = end_date.strftime("%#d %b %Y, at %I:%M%p")
            await conn.fetch(f"UPDATE blacklist SET time={end_date} WHERE username={member.id}")
        
            await member.add_roles(restricted, reason=f'Restricted role added by {author.name}')
            await member.remove_roles(members)
            
            await conn.close()

            msg = f"{member} has been restricted until {fmt_date}."
            embed = discord.Embed(title="Restricted", description=msg, colour=author.color)
            await ctx.send(embed=embed)
            return
4

1 回答 1

0

f-strings在处理 SQL 查询时,您不传递参数,查询参数的语法asyncpg$n,我也看到您正在使用该Connection.fetch方法,但您只是在更新表,我建议您使用Connection.execute

您的代码已修复:

end_date = # Should be a datetime.datetime instance
await conn.execute("""
    UPDATE blacklist 
    SET time = $1 
    WHERE username = $2
""", end_date, member.id)

消除时区意识

end_date = # `datetime.datetime` instance
naive = end_date.replace(tzinfo=None)
await conn.execute("""
    UPDATE blacklist 
    SET time = $1 
    WHERE username = $2
""", naive, member.id)

参考:

PS:不要每次想用都新建一个连接,正常做法是一个长期数据库连接

于 2021-04-12T17:57:59.617 回答