当前位置:网站首页>Detailed explanation of two methods of Sqlalchemy
Detailed explanation of two methods of Sqlalchemy
2022-07-27 08:59:00 【IChocolateKapa】
Work needs , Yes sqlalchemy, After nearly a month of continuous learning, exploration and practice , Now tidy up , In case there is no place to look for .
sqlalchemy There are two ways , One is session-mapper The way , be called orm The way , The other is native select etc. sql sentence , be called core The way .
In the following explanation, we uniformly encapsulate the related operations of the database in a class .
Let's start with the first :
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.mysql import INTEGER, DATETIME, REAL, TEXT, VARCHAR
from sqlalchemy import Table, Column, ForeignKey, MetaData
from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import func
import re
import hashlib
import os, sys
import time, datetime
class SelectData():
def __init__(self):
s1 = "mysql+mysqldb://"
server = "root:[email protected]:3306/test"
s2 = "?use_unicode=0&charset=utf8"
connectserver = s1 + server + s2
self.engine = create_engine(connectserver, encoding = 'utf-8', echo = False)
self.Base = MetaData()
self.user= Table(
'user', self.Base,
Column('id', INTEGER, primary_key = True),
Column('name', TEXT)
Column('passwd', TEXT)
)
self.client = Table(
'client', self.Base,
Column('id', INTEGER, primary_key = True),
Column('name', TEXT),
Column('id_user', INTEGER),
Column('reserved_int', INTEGER),
Column('reserved_varchar', VARCHAR(200))
)
self.Base.create_all(self.engine)#create_all It can automatically detect whether the table has been established , Very convenient
self.Session = sessionmaker() # Created a customized Session class
self.Session.configure(bind = self.engine) # Associate the created database connection to this sessionThe following function shows the query insertion update of a single table :
def insert_function(self):
session = self.Session()
class User(object): pass
mapper(User, self.user)
class Client(object): pass
mapper(Client, self.client)
#select The way :
ret = session.query(User).filter(User.name == "admin").first()
if ret is None:
# Add new fields
user = User()
user.name = "admin"
user.passwd = CountMd5("123456")# here CountMd5() It's a calculation written by myself md5 The value of the function
session.add(user)
session.flush()
#session.commit()
# Get the self incrementing primary key of the data just inserted id
id_usr = user.id
else:
id_usr = ret.id
ret2 = session.query(Client).filter_by(id_user = id_usr).first()
if ret2 is None:
client = Client()
client.name = "Chocolate"
client.id_user = id_usr
client.session.add(client)
session.flush()
session.commit()
else:
# Use update:
session.query(Client).filter_by(id_user = id_usr).update({"name": "Chocolate", "id_user":id_usr})
session.flush()
session.commit()
session.close()The following is multi table joint query :
# Multi table joint query
def testfun2(self, partname, pageindex):
session = self.Session()
class User(object): pass
mapper(User, self.user)
class Client(object): pass
mapper(Client, self.client)
pageval = (pageindex - 1) * 10
# One of them is like Usage of , One is to show only a 10 strip
ret = self.session.query(User)\
.join(Client, Client.id_user == User.id )\
.filter(User.name.like('%' + partname + '%'))\
.offset().limit(10).all()
if ret is None:
return None
else:
for k in ret:
print k.name, k.passwd
session.close()The following is the usage of deleting the contents of the table :
# Delete all contents of the table , Don't delete the table
def delete_func(self):
session = self.Session()
class User(object): pass
mapper(User, self.user)
class Client(object): pass
mapper(Client, self.client)
session.query(Client).delete()
session.query(User).delete()
session.commit()
session.close() Above is orm The way of the , What we should pay special attention to in this way is ,session The problem of , because session It has a valid period , If we put session stay init The function is made into a global variable self.session, Then the database will update the inserted value in real time, which cannot be queried , therefore , about session The attitude of , We use and then build , Close manually after use . Then let's talk about the second way ,core The way :
The above table building part is the same , It's just that after the table is built session Replace that piece with :
self.Base.create_all(self.engine)
self.conn = self.engine.connect()def close(self):
self.conn.close()Contains the query , Insert and update .
def resetpwd(self, passwdm):
sel = select([self.user]).where(self.user.c.name == "admin")
ret = self.conn.execute(sel).fetchone()
if ret is None:
ins = self.user.insert().values(name = "admin", passwd = passwdm)
self.conn.execute(ins)
else:
updpwd = self.user.update().values(name = "admin", passwd = passwdm).where(self.user.c.name == "admin")
self.conn.execute(updpwd)execute automatically commit, We don't have to do it manually . such core The way we should pay attention to is that there is a .c, Such as self.user.c.name, I don't know why there is this c, Look at the use cases on the official website , If you don't add it, it's not correct . So surrender to authority . The most important thing is to solve the problem .
That's all . I hope you can make progress together !
Reprint an article , Please indicate the source .
边栏推荐
猜你喜欢

View 的滑动冲突

NIO示例

async/await的执行顺序以及宏任务和微任务

CUDA programming-02: first knowledge of CUDA Programming

String type and bitmap of redis

4276. Good at C

NIO this.selector.select()

E. Split into two sets

Intel, squeezed by Samsung and TSMC, finally put down its body to customize chip technology for Chinese chips

NIO总结文——一篇读懂NIO整个流程
随机推荐
Tensorflow package tf.keras module construction and training deep learning model
Low cost, low threshold, easy deployment, a new choice for the digital transformation of 48 million + small and medium-sized enterprises
02 linear structure 3 reversing linked list
[I2C reading mpu6050 of Renesas ra6m4 development board]
TensorFlow损失函数
MySQL basic knowledge learning (I)
Flask login implementation
NiO Summary - read and understand the whole NiO process
redis 网络IO
Interface test tool -postman usage details
Redis network IO
【每日算法Day 94】经典面试题:机器人的运动范围
低成本、低门槛、易部署,4800+万户中小企业数字化转型新选择
1.3.1 Full Permutation Problem
如何在B站上快乐的学习?
“蔚来杯“2022牛客暑期多校训练营1
5G没能拉动行业发展,不仅运营商失望了,手机企业也失望了
【进程间通信IPC】- 信号量的学习
Deep understanding of Kalman filter (3): multidimensional Kalman filter
Deep understanding of Kalman filter (2): one dimensional Kalman filter