skip to Main Content

There’s a problem – for some reason I don’t understand, the code doesn’t want to write a value to the database. The concept of the code is as follows – a person sends a message and the bot writes his message to the database. If there is an error in the code, it writes "ERR". But the bot at the stage of sending the message, is just not going to send the data to the database, it doesn’t even give any sending sign. Thanks for any help 🙌

Code:

@dp.message_handler(Text(equals="Buy"))
async def with_pureee(message: types.Message):
    await message.reply("Loading...")
    keyboard = ReplyKeyboardRemove()
    back = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
    buttons = ["back"]
    back.add(*buttons)
    await message.answer("Please, write your name", reply_markup=back)
    @dp.message_handler()
    async def names(message: types.Message):
        mes = message.text
        if mes == "Back":
            return
        else:
            try:
                conn = await aiomysql.connect(host='localhost', port=3306,
                                           user='root', password='', db='aiodb', loop=loop)
                cur = await conn.cursor()
                await cur.execute("INSERT INTO users(name) values(msg)")
                await conn.commit()
                await cur.close()
            except Exception as e:
                @dp.message_handler()
                async def names(message: types.Message):
                    await message.answer("ERR")

2

Answers


  1. Look at the following line of code

    await cur.execute("INSERT INTO users(name) values(msg)")
    

    The name field must be a string so it should have single quotes ‘msg’ or it could be that you were trying to pass a variable into the statement. That should be done differently. See here

    await cur.execute("INSERT INTO users(name) values('msg')")
    

    In addition, look at the error trapping. Ensure that it return the actual error and not a generic error message like ‘ERR’

    Login or Signup to reply.
  2. Rewrite your code like this and all works.

    @dp.message_handler(text="Buy")
    async def with_pureee(message: types.Message, state: FSMContext):
        await message.reply("Loading...")
        keyboard = ReplyKeyboardRemove()
        back = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
        # buttons = ["back"] - here was a mistake, lowercase instead of capitalized
        buttons = ["Back"]
        back.add(*buttons)
        await message.answer("Please, write your name", reply_markup=back)
        await state.set_state('get_name')
        
    
    @dp.message_handler(state='get_name')
    async def names(message: types.Message, state: FSMContext):
        mes = message.text
        if mes == "Back":
            await state.finish()
        else:
            try:
                conn = await aiomysql.connect(host='localhost', port=3306,
                                               user='root', password='', db='aiodb', loop=loop)
                cur = await conn.cursor()
                await cur.execute("INSERT INTO users(name) VALUES ({})".format(mes))
                await conn.commit()
                await cur.close()
                
                await message.answer(f'user {mes} added')
            except Exception as e:
                await message.answer(f"ERR {e}") # add 'e' to watch the error description
            finally:
                conn.close()
                await state.finish()
    

    It’s better to use FSM to get info from user.

    Also you could rewrite this:

    await cur.execute("INSERT INTO users(name) VALUES (" + mes + ")") 
    await conn.commit() 
    await cur.close()
    

    like this:

    async with conn.cursor() as cur:
        await cur.execute("INSERT INTO users(name) VALUES (" + mes + ")")
    

    so you don’t need to close connection.


    aiomysql tutorial has lots of examples, for example
    inserting data

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search