ORM
程序员文章站
2022-04-19 07:58:39
...
pymysql处理事件时:
# pymysql-event
import pymysql
# 涉及到写操作的需要commit
db = pymysql.connect(host="localhost",user="root",password="123456",
database="studentInfo",port=3306,charset="utf8")
cursor = db.cursor()
try:
ins = "insert into t1 values(2,'小姐姐',88)"
cursor.execute(ins)
upd = "update t1 set score=100 where name='小姐姐'"
cursor.execute(upd)
dele = "delete from t1 where id=1"
cursor.execute(dele)
db.commit()
except Exception as e:
db.rollback()
print("Failed:",e)
cursor.close()
db.close()
# pymysql-event
import pymysql
# 涉及到读操作的不需要commit
db = pymysql.connect(host="localhost",user="root",password="123456",
database="studentInfo",port=3306,charset="utf8")
cursor = db.cursor()
try:
sel = "select * from t1 name like '小姐姐%'"
cursor.execute(sel)
res = cursor.fetchall()
except Exception as e:
db.rollback()
print("Failed:",e)
cursor.close()
db.close()
ORM 框架
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy import Integer,String,Column,create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
#与数据库连接对象
# engine = create_engine("mysql+pymysql://root:[email protected]:3306/test",encoding="UTF-8",echo=True) “echo=True” 显示底层的SQL语句
engine = create_engine("mysql+pymysql://root:[email protected]:3306/test",encoding="UTF-8",echo=True)
#创建session会话类
DBsession = sessionmaker(bind=engine)
session = DBsession() #session实例
#创建ORM基类
Base = declarative_base()
#继承基类
class Student(Base):
__tablename__ = "student"
id = Column(Integer,primary_key=True)
name = Column(String(20))
phnumber = Column(String(11),unique=True)
def __init__(self,name,phnumber):
self.name = name
self.phnumber = phnumber
Base.metadata.create_all(engine)
# student1 = Student("Lily","15114827769")
# student2 = Student("Lucy","17671228934")
# session.add_all([student1,student2])
# session.commit()
st = session.query(Student).filter_by(id=1).first()
print("姓名:%s,年龄:%s" % (st.name,st.phnumber))
上一篇: 如何用SQL语句去掉重复记录
下一篇: 删除表数据零基础入门教程汇总
推荐阅读
-
laravel5.6 框架操作数据 Eloquent ORM用法示例
-
深浅赋值+orm操作+Django-admin简单配置
-
asp.net core系列 66 Dapper介绍--Micro-ORM
-
Laravel框架Eloquent ORM新增数据、自定义时间戳及批量赋值用法详解
-
Django使用详解:ORM 的反向查找(related_name)
-
Laravel框架Eloquent ORM修改数据操作示例
-
Django视图之ORM数据库查询操作API的实例
-
C#使用sqlite-net搭建简易的ORM
-
ADO.NET ORM数据库增删改查封装(工具一)
-
Django---ORM中的锁和事务