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
Look at the following line of code
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
In addition, look at the error trapping. Ensure that it return the actual error and not a generic error message like ‘ERR’
Rewrite your code like this and all works.
It’s better to use FSM to get info from user.
Also you could rewrite this:
like this:
so you don’t need to close connection.
aiomysql tutorial has lots of examples, for example
inserting data