一,安装SQLAlchemy
1,用pip安装
(venv) [liuhongdi@img news]$ pip3 install sqlalchemy
2,安装完成后查看已安装的版本:
(venv) [liuhongdi@img news]$ pip3 show sqlalchemy
Name: SQLAlchemy
Version: 2.0.27
Summary: Database Abstraction Library
Home-page: https://www.sqlalchemy.org
Author: Mike Bayer
Author-email: [email protected]
License: MIT
Location: /web/site/python/news/venv/lib/python3.11/site-packages
Requires: greenlet, typing-extensions
Required-by:
二,安装pymysql
1,用pip安装pymysql库
(venv) liuhongdi@192 news % pip3 install pymysql
2,查看已安装库的信息
(venv) liuhongdi@192 news % pip3 show pymysql
Name: PyMySQL
Version: 1.1.0
Summary: Pure Python MySQL Driver
Home-page:
Author:
Author-email: Inada Naoki <[email protected]>, Yutaka Matsubara <[email protected]>
License: MIT License
Location: /Users/liuhongdi/python_work/tutorial/news/venv/lib/python3.12/site-packages
Requires:
Required-by:
说明:刘宏缔的架构森林—专注it技术的博客,
网址:https://imgtouch.com
本文: https://blog.imgtouch.com/index.php/2024/02/19/python-shi-zhan-yong-sqlalchemy-zuo-orm/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: [email protected]
三,看一个简单的例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
from sqlalchemy import Column, Integer, String
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import declarative_base
import os
import sys
# 打印文件的目录路径(文件的上两层目录)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# 将这个路径添加到环境变量中。
sys.path.append(BASE_DIR)
host = conf_node[ 'host' ]
port = conf_node[ 'port' ]
user = conf_node[ 'user' ]
pswd = conf_node[ 'password' ]
base = conf_node[ 'database' ]
char = conf_node[ 'charset' ]
# 得到数据库实例
db = create_engine( 'mysql+pymysql://' , connect_args = { 'user' : user,
'password' : pswd,
'host' : host,
'port' : 3306 ,
'database' : base,
'charset' : char})
# 建立映射关系
Base = declarative_base()
# 定义类
class News(Base):
__tablename__ = 'news' # 设置表明
id = Column(Integer, primary_key = True )
title = Column(String( 500 ))
url = Column(String( 500 ))
# 创建会话
obj_session = sessionmaker(db)
# 打开会话
db_session = obj_session()
# 查询表中所有数据
all_list = db_session.query(News). all ()
for obj in all_list:
print ( "id:" , obj. id )
print ( "title:" , obj.title)
print ( "url:" , obj.url)
# 关闭会话
db_session.close()
|
运行结果:
(venv) [liuhongdi@img news]$ python3 lib/mysql/connection.py
id: 1
title: 新浪微博
url: https://weibo.com
id: 2
title: 百度
url: https://baidu.com