对象关系映射(Object Relational Mapping,ORM),将对数据库的操作,映射为对类的操作,一个表对应一个类。sqlalchemy无法独立对数据库进行操作,需要借助其他第三方插件,这里我运用了pymysql。
sqlalchemy建议安装1.3.15版本,太旧的版本可能会出现报错。
由于要做类映射,对表new_table 增加了一列主键
alter table newtable add id int unsigned not Null auto_increment primary key;
import sqlalchemy
print(sqlalchemy.__version__)
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String
from sqlalchemy.orm import sessionmaker
from sqlalchemy import and_, or_
ip ='127.0.0.1'
port = '3306'
db = 'test_databases'
user = 'root'
passwd = '3gynj20J'
DB_URI ='mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(user,passwd,ip,port,db)
engine=create_engine(DB_URI)
print(engine) # Engine(mysql+pymysql://root:***@127.0.0.1:3306/test_databases?charset=utf8)
Base = declarative_base(engine) #创建基类,所有表对应的类必须继承自这个基类
# 创建会话
Session = sessionmaker(engine)
# 此条必须,每次执行数据库操作时,都需要创建一个Connection
session = Session()
# 创建表对应的类
class New_Table(Base):
__tablename__ = 'newtable'
id = Column(Integer,nullable=False,primary_key=True, autoincrement=True)
key1 = Column(String(20),nullable=False)
key2 = Column(Integer,nullable=False)
def add_1(a,b):
row = New_Table(key1=a,key2=b)
session.add(row)
session.commit()
# add_1('test',0)
def add_N(List):
tmp=[]
for item in List:
row = New_Table(key1=item[0],key2=item[1])
tmp.append(row)
session.add_all(tmp)
session.commit()
# add_N([['BB',22],['CC',33]])
def search():
#查所有
re = session.query(New_Table).filter_by(key2 =22).all() # 返回一系列对象的列表
re = session.query(New_Table).filter(New_Table.key2==22).all()
# print(re[0].id)
#查第一条
re =session.query(New_Table).filter_by(key2 =22).first()
# print(re.id)
# #查一条
re =session.query(New_Table).filter_by(key2 =22).one()
# print(re.id)
re =session.query(New_Table).get(6) # 用主键查
# print(re.key2)
#查0或1
re = session.query(New_Table).filter_by(key2 =22).scalar() # 若存在为一个对象,若不存在则为None
# print(re.id)
# search()
def update(a,b):
session.query(New_Table).filter_by(key1=a).update({New_Table.key1:a,New_Table.key2:b}) # update 里的字典可不写全
session.query(New_Table).filter_by(key1=a).update({New_Table.key2: b+1})
session.commit()
# return
# update('BB',100)
def delete(a):
re=session.query(New_Table).filter_by(key1=a).one()
session.delete(re)
session.commit()
# delete('test')
#与或非
def and_or(a,b):
# re = session.query(New_Table).filter(and_(New_Table.key1==a,New_Table.key2==b)).one()
# print(re.id)
re = session.query(New_Table).filter(or_(New_Table.key2 == a, New_Table.key2 == b)).all()
print([i.id for i in re])
# and_or('BB',101)
and_or(2,33)
1、could not assemble any primary key columns for mapped table 'newtable'
原来的表没有主建,用alter语句增加一列主键即可
alter table newtable add id int unsigned not Null auto_increment primary key;
2、Unknown system variable 'tx_isolation sqlalchemy
安装的sqlalchemy 太旧了,升级一下。
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade sqlalchemy --ignore-installed
https://blog.csdn.net/qq_36019490/article/details/96883453