1.连接数据库
from sqlalchemy import create_engine
# 连接数据库
engine = create_engine('mysql+pymysql://username:password@localhost/dbname')
# 进行一些数据库操作
# ...
# 关闭连接
engine.dispose()
mysql:数据库类型;
pymysql:MySQL数据库驱动;
username:数据库用户名;
password:数据库密码;
localhost:数据库主机名;
dbname:数据库名。
2.查询数据
SQLAlchemy提供了两种查询数据的方式:基于SQL语句的查询和基于ORM的查询。
基于SQL语句的查询
from sqlalchemy import create_engine
# 连接数据库
engine = create_engine('mysql+pymysql://username:password@localhost/dbname')
# 执行查询语句
result = engine.execute("SELECT * FROM employees")
# 处理查询结果
for row in result:
print(row)
# 关闭连接
engine.dispose()
-------------------------------------------------------