您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“python如何利用sqlalchemy操作數(shù)據(jù)庫(kù)”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
1.安裝
pip install sqlalchemy
2.代碼如下
#!/usr/bin/python
# coding=utf-8
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Integer, String, DateTime, Boolean
engine = create_engine("mysql://root:root@127.0.0.1:3306/test?charset=utf8")
Session = sessionmaker(bind=engine)
Base = declarative_base()
class News(Base):
''' 新聞?lì)愋?'''
__tablename__ = 'news'
id = Column(Integer, primary_key=True)
title = Column(String(200), nullable=False)
content = Column(String(2000), nullable=False)
types = Column(String(10), nullable=False)
image = Column(String(300))
author = Column(String(20))
view_count = Column(Integer)
created_at = Column(DateTime)
is_valid = Column(Boolean)
class MysqlOrmTest(object):
def __init__(self):
self.session = Session()
def add_one(self):
new_obj = News(
title='orm title',
content='content',
types='百家'
)
self.session.add(new_obj)
self.session.commit()
return new_obj
def get_one(self):
''' 獲取一條數(shù)據(jù) '''
return self.session.query(News).get(1)
def get_more(self):
''' 獲取多條數(shù)據(jù) '''
return self.session.query(News).filter_by(is_valid=1)
def update_data(self):
''' 修改數(shù)據(jù) '''
obj = self.session.query(News).get(38)
obj.is_valid = 0
self.session.add(obj)
self.session.commit()
return obj
def delete_data(self):
''' 刪除數(shù)據(jù) '''
# 獲取要?jiǎng)h除的數(shù)據(jù)
data = self.session.query(News).get(39)
self.session.delete(data)
self.session.commit()
def main():
obj = MysqlOrmTest()
# rest = obj.add_one()
# print(dir(rest))
# print(obj.get_one().title)
# print(obj.get_more().count())
# for row in obj.get_more():
# print(row.title)
# print(obj.update_data())
obj.delete_data()
if __name__ == '__main__':
main()
“python如何利用sqlalchemy操作數(shù)據(jù)庫(kù)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。