Uncategorized

mysql – SQLAlchemy cant find certain values in my tables (Python)


This is something I just stumbled upon as a weird exception. Basically I have a bot that I send a slash command to (discord.py) and it takes that username and queries a MySQL table I have. This works for nearly all usernames I have tested including my own–vxnii–but just today I was trying to actually use it and attempted to send the request with the username ‘1ooh’, and no matter what I tried I could not get it to work, not sure if its a quirk with SQLAlchemy or what.

Here is the function:

@app_commands.command(description="Checks keys belonging to a user.")
    @is_owner()
    async def keys(self, interaction: discord.Interaction, member: discord.Member):
        user = member
        print(member)
        try:
            await interaction.response.defer()
            duser = session.query(Discord).ilike(username=str(user.name).strip()).first()
            print(duser)
            keyEmbed = discord.Embed(title=duser.key, description=f"{user.mention}'s Keys.", color=0x3498db)
            await interaction.followup.send(embed=keyEmbed)
        except AttributeError as E:
            print(E)

So I have access to the table through MySQL workbench and can 100% confirm the value exists and when I search for it in the workbench it comes right up and is clean with no spaces on either side of it. I tried a few variations of this one using just like instead of ilike

duser = session.query(Discord).like(username=str(user.name).strip()).first()

aswell as just

duser = session.query(Discord).filter_by(username=str(user.name).strip()).first()

None of these worked, however I did find a solution eventually:

 @app_commands.command(description="Checks keys belonging to a user.")
    @is_owner()
    async def keys(self, interaction: discord.Interaction, member: discord.Member):
        user = member
        sname = str(user.name).strip()
        print(sname)
        try:
            await interaction.response.defer()
            query = text("SELECT * FROM discord WHERE username LIKE :sname")
            duser = session.execute(query, {"sname": f"%{sname}%"}).fetchone()
            print(duser)
            keyEmbed = discord.Embed(title=duser.key, description=f"{user.mention}'s Keys.", color=0x3498db)
            await interaction.followup.send(embed=keyEmbed)
        except AttributeError as E:
            print(E)

Using a raw SQL query which should do the same thing as the .like query type I managed to get it to return the intended result. Anyway I do have a solution so thats good, but I am really interested if anyone knows why this is acting as it is, or maybe im just missing something super obvious.

(What I mean by not working is it returning ‘None’ when searhcing with the above queries)



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *