Python to MySQL database connection by SQLAlchemy with error handling using try except blocks

preview_player
Показать описание

List of all Python MySQL tutorials

We can connect to MySQL database by using SQLAlchemy connect_engine from Python. This uses mysqlclient library to connect to MySQL database. The connection engine created can be further used to handle database queries.
Here is a simple connection string
from sqlalchemy import create_engine
After successful connection we can test the query by taking data from our sample table student.
SELECT * FROM student LIMIT 0,5
We can display five records from our student table by using the above query. Here is the complete code.
q="SELECT * FROM student LIMIT 0,5"
print(type(rs))

print(type(rs))
for row in rs:
print(row)
Handling error
WE can display any error message by using try except code block. Here is a sample block using error handling.

q="SELECT * FROM student LIMIT 0,10"
try:
except SQLAlchemyError as e:
error=str(e.__dict__['orig'])
print(error)
except Exception as e:
print(e)
else:
Рекомендации по теме
Комментарии
Автор

How to check whether user has entered correct username and password in create_engine method ?

striver
Автор

Hi! Thanks for the video. I'm attempting to connect with MySQL using the very same method as the one described on this video, but I'm getting the next error:

Exception has occurred: NameError
name '_mysql' is not defined

I've already googled it, but cannot find any possible solution for it. I was wondering if you could guess what's going on or had the same issue in the past. Thanks!

oportoalonso
welcome to shbcf.ru