学习www.网for站asp制.cn作
python,使用 create_engine 用字符串模式连接mysql 数据库,如果密码有特殊符号会被当作连接符无法连接。
 
比如python原始代码:
 
from sqlalchemy import create_engine
 
username = 'test_deepdata'
password = 'test123!@'
host = '192.168.1.114'
port = 3308
database = 'testdb'
 
# Create the connection string
connection_string = f'mysql+pymysql://{username}:{password}@{host}:{port}/{database}'
 
# Create the SQLAlchemy engine
engine = create_engine(connection_string)
 
在 connection_string中的password也有个 @ 符号,那么就和后面的符号重复了,导致连接失败。
 
 
修改使用 quote_plus 来解决该特殊符号问题,修改后代码如下:
from sqlalchemy import create_engine
# 引入转译函数
from urllib.parse import quote_plus
 
# 进行特殊符号转译
password_encoded = quote_plus(password)
 
connection_string = f'mysql+pymysql://{username}:{password_encoded}@{host}:{port}/{database}'
 
这样就可以使用特殊符号作为密码来进行操作了。