安装环境 WSL
bash
>wsl -l -v
NAME STATE VERSION
* Ubuntu-18.04 Running 1
WSL2 无法与windows通信
bash
>wsl -l -v
NAME STATE VERSION
* Ubuntu-18.04 Running 2
解决方案1:设置防火墙,参考解决WSL与window通信问题
解决方案2:将wsl版本降级为1,等待20分钟左右,即可执行成功
bash
>wsl --set-version Ubuntu-18.04 1
Python 配置MySQL
安装依赖
- 配置requirements.txt
bash
sqlalchemy-utils==0.41.1
sqlalchemy==2.0.29
pymysql==1.0.2
- 安装依赖
bash
pip install -r requirements.txt -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
配置MySQL
python
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
def get_db_session(host: str, port: str, username: str, password: str, database_name: str) -> Session:
engine = create_engine(f'mysql+pymysql://{username}:{password}@{host}:{port}/{database_name}')
session_maker = sessionmaker(autocommit=False, autoflush=False, bind=engine)
return session_maker()
def get_db_engine(host: str, port: str, username: str, password: str, database_name: str):
engine = create_engine(f'mysql+pymysql://{username}:{password}@{host}:{port}/{database_name}')
return engine
代码示例
python
# 使用方式1
engine = get_db_engine(host, port, username, password, database_name)
Session = sessionmaker(bind=engine)
session1 = Session()
result1 = session1.execute(text("select * from table1"))
# 遍历结果集并打印每一行
for row in result1:
print(row)
# 使用方式2
session2 = get_db_session(host, port, username, password, database_name)
result2 = session2.execute(text("select * from table1"))
# 遍历结果集并打印每一行
for row in result2:
print(row)