网站制作学习网Python→正文:python 连接mysql密码特殊符号
字体:

python 连接mysql密码特殊符号

Python 2024/9/2 15:43:33  点击:不统计

学习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}'
 
这样就可以使用特殊符号作为密码来进行操作了。
 

·上一篇:python 中的strip >>    ·下一篇:python 获取属性简洁方法 >>
推荐文章
最新文章