SQLAlchemy是什么
現(xiàn)在很多的企業(yè)進(jìn)行后端開發(fā)時,程序員在分析完業(yè)務(wù)后,會使用Java的SpringBoot或者Python的Django、Flask等網(wǎng)絡(luò)框架進(jìn)行項目開發(fā)。在這些網(wǎng)絡(luò)框架業(yè)務(wù)邏輯代碼編寫的過程中,很大概率會需要使用到MySQL數(shù)據(jù)庫,但是原生的SQL語句又存在被SQL注入的風(fēng)險,而且在復(fù)雜的查詢時,SQL語句也會變的復(fù)雜,可讀性隨之降低。
那么框架的開發(fā)人員引進(jìn)了一種叫ORM的概念(Object Relational Mapping)。這種概念是對象與關(guān)系式數(shù)據(jù)庫的一種映射,簡單的來說就是使用類(class)來進(jìn)行一個數(shù)據(jù)庫的映射。類名可以是表名,而類內(nèi)部的屬性就是數(shù)據(jù)庫中的字段。文章來源:http://www.zghlxwxcb.cn/news/detail-467639.html
下面是一個示例代碼,使用SQLAlchemy實現(xiàn):文章來源地址http://www.zghlxwxcb.cn/news/detail-467639.html
# 導(dǎo)入必要的庫
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
# 創(chuàng)建數(shù)據(jù)庫引擎
engine = create_engine('sqlite:///articles.db', echo=True)
# 創(chuàng)建會話對象
Session = sessionmaker(bind=engine)
session = Session()
# 創(chuàng)建數(shù)據(jù)模型基類
Base = declarative_base()
# 創(chuàng)建文章模型類
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())
# 創(chuàng)建表結(jié)構(gòu)
Base.metadata.create_all(engine)
# 創(chuàng)建一篇新文章
new_article = Article(
title='SQLAlchemy入門教程',
author='張三',
content='SQLAlchemy是一個Python ORM框架,可以方便地實現(xiàn)與數(shù)據(jù)庫的交互。'
)
# 將文章添加到數(shù)據(jù)庫中
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}')
到了這里,關(guān)于python使用SQLAlchemy進(jìn)行mysql的ORM操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!