使用sqlalchemy的增刪改查

2021-08-17 01:34:16 字數 2885 閱讀 2198

from connect import base,session

from sqlalchemy import column,integer,string,datetime,boolean

from datetime import datetime

class

user

(base):

__tablename__='user'

#__tablename__定義表名字

id = column(integer,primary_key=true,autoincrement=true)

username = column(string(20),nullable=false)

password = column(string(50))

createtime = column(datetime,default=datetime.now())

_locked = column(boolean,default=false,nullable=false)

@classmethod #查詢所有的靜態類方法

defall

(cls):

return session.query(cls).all()

@classmethod #filter_by所有的靜態類方法id

defby_id

(cls,id):

return session.query(cls).filter_by(id=id).all()

@classmethod #縮寫查詢的username的方式

defby_name

(cls,name):

return session.query(cls).filter_by(username=name).all()

@property

deflocked

(self):

return self._locked

def__repr__

(self):

return

"" % (

self.id ,

self.username,

self.password,

self.createtime,

self._locked

)#定義原生型別,不定義會返回乙個物件

if __name__=='__main__':

base.metadata.create_all()

sqlalchemy的增刪改查
@classmethod   #查詢所有的靜態類方法

defall

(cls):

return session.query(cls).all()

@classmethod #filter_by所有的靜態類方法id

defby_id

(cls,id):

return session.query(cls).filter_by(id=id).all()

@classmethod #縮寫查詢的username的方式

defby_name

(cls,name):

return session.query(cls).filter_by(username=name).all()

@property

deflocked

(self):

return self._locked

需要session 會話呼叫

from user_modules import user,session

defadd_user

():# person =user(username='dandan',password='abc123')

# session.add(person)

session.add_all(

[user(username='tobee',password='234qwe'),

user(username='no1',password='zzz123')

]) #新增多個元素

session.commit()

defsearch_user

(): row = session.query(user).all()

# print(row)

row = session.query(user).filter_by(id=1).all() #filter_by與filter的區別

# print(row)

row = session.query(user).filter(user.username=='no1')

print(row[0].locked)

defupdate_user

(): row = session.query(user).filter_by(username='dandan').update()

session.commit()

defdelete_user

(): row = session.query(user).filter_by(username='no1')[0]

print(row)

session.delete(row)

session.commit()

if __name__=="__main__":

# add_user()

# search_user()

# update_user()

delete_user()

# print(user.all())

# print(user.by_id(1))

print(user.by_name('no1'))

# print(dir(row[0]))

sqlalchemy原始增刪改查方法

coding utf 8 from sqlalchemy import create engine from sqlalchemy.ext.declarative import declarative base from sqlalchemy import column,integer,string...

flask 與 SQLAlchemy的使用

安裝模組 pip install flask sqlalchemy在單個python中與flask使用 檔名 manage.py from flask sqlalchemy import sqlalchemy from flask import flask user root password ro...

SQLAlchemy模組的使用教程

資料庫表是乙個二維表,包含多行多列。把乙個表的內容用python的資料結構表示出來的話,可以用乙個list表示多行,list的每乙個元素是tuple,表示一行記錄,比如,包含id和name的user表 1 michael 2 bob 3 adam python的db api返回的資料結構就是像上面這...