Using sqlalchemy to operate the database in python encounters a password containing @ processing method

When using sqlalchemy to operate the database, an error will be reported when the password contains @. Because it uses @ to link the IP address, if there is @ in the password, it will be confused with the @ in the grammar. The editor will report an error.

For example, the following example:
Username: XXXXX
Password: 123@abc
IP address: 127.0.0.1
Database port: 3308
Database name: hehemall

con_info = 'mysql+pymysql://XXXXX:123@[email protected]:3308/hehemall?charset=utf8'
# 语法:con_info ='mysql+pymysql://数据库用户:密码@IP地址:端口/数据库名?charset=utf8'

There is an @ in the password, and there is a fixed @ in the grammar, which will be spliced ​​according to @, so that when the @ in the password is run, the code thinks that the latter should be an IP address. But in reality that's just one character in the password.

Using the above method to connect to the database will report an error:

sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, 'Can\'t connect to MySQL server on \'abc"@127.0.0.1\' ([Errno 8] nodename nor servname provided, or not known)')

Parsing issues caused by the @ symbol

How to solve?
Use the encoding method provided in python's urllib library, the code is as follows

from urllib.parse import quote_plus as urlquote

host="127.0.0.1"
port=3308
user="XXXXX"
password="123@abc"
db_name="hehemall"
con_info = f'mysql+pymysql://{
      
      user}:{
      
      urlquote(password)}@{
      
      host}:{
      
      port}/{
      
      db_name}?charset=utf8'

Guess you like

Origin blog.csdn.net/xkukeer/article/details/127806164