SQLAlchemy是什么
现在很多的企业进行后端开发时,程序员在分析完业务后,会使用Java的SpringBoot或者Python的Django、Flask等网络框架进行项目开发。在这些网络框架业务逻辑代码编写的过程中,很大概率会需要使用到MySQL数据库,但是原生的SQL语句又存在被SQL注入的风险,而且在复杂的查询时,SQL语句也会变的复杂,可读性随之降低。
那么框架的开发人员引进了一种叫ORM的概念(Object Relational Mapping)。这种概念是对象与关系式数据库的一种映射,简单的来说就是使用类(class)来进行一个数据库的映射。类名可以是表名,而类内部的属性就是数据库中的字段。文章来源:https://www.toymoban.com/news/detail-467639.html
下面是一个示例代码,使用SQLAlchemy实现:文章来源地址https://www.toymoban.com/news/detail-467639.html
# 导入必要的库
from sqlalchemy import Column, Integer, String, DateTime, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime
# 创建数据库引擎
engine = create_engine('sqlite:///articles.db', echo=True)
# 创建会话对象
Session = sessionmaker(bind=engine)
session = Session()
# 创建数据模型基类
Base = declarative_base()
# 创建文章模型类
class Article(Base):
__tablename__ = 'articles'
id = Column(Integer, primary_key=True)
title = Column(String)
author = Column(String)
content = Column(String)
created_at = Column(DateTime, default=datetime.now())
# 创建表结构
Base.metadata.create_all(engine)
# 创建一篇新文章
new_article = Article(
title='SQLAlchemy入门教程',
author='张三',
content='SQLAlchemy是一个Python ORM框架,可以方便地实现与数据库的交互。'
)
# 将文章添加到数据库中
session.add(new_article)
session.commit()
# 查询所有文章
articles = session.query(Article).all()
# 打印所有文章
for article in articles:
print(f'Title: {article.title}, Author: {article.author}, Content: {article.content}, Created At: {article.created_at}')
到了这里,关于python使用SQLAlchemy进行mysql的ORM操作的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!