连接数据库的另外一种方式 ORM 模型

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import json

# 将这些信息写在一个配置文件 (这里面写到了 json 文件中)
setting_file = r"F:\python_prj\hsh_rk2\setting.json"
setting_json = json.load(open(setting_file))
db = setting_json.get('mysql').get('hsh_zt')
print(db)  # {'charset': 'utf8', 'host': '127.0.0.1:3306', 'db': 'haha', 'pwd': 'root', 'user': 'root'}

# 连接数据库
"""
       pymysql
            mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]

            mysql+pymysql://用户名 : 密码  @ip+port/ 数据库名称 [?<options>]

       # 创建引擎
            engine = create_engine("mysql+pymysql://root:[email protected]:3306/ccc", max_overflow=5, encoding='utf-8', echo=True)
"""
engine_str = 'mysql+pymysql://{}:{}@{}/{}?charset={}'.format(db.get('user'), db.get('pwd'), db.get('host'), db.get('db'), db.get('charset'))
engine = create_engine(engine_str, echo=True)     # echo=True  这个参数显示 生成的过程
DB_Session = sessionmaker(bind=engine)            # 创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例
session = DB_Session()                            # 生成session实例 #cursor
sql = "select * from table_haha"                # 定义一个 sql 语句
result = session.execute(sql)                    # 提交sql语句
result_list = list(result)                       # 将获取到的结果转化成一个列表

ORM框架很多的知识,我是学的有点头大,看过了我又忘记的差不多了,没完整的用过还是记不住,只能说有点印象。。。

猜你喜欢

转载自blog.csdn.net/chang995196962/article/details/83506919