diff --git a/sqlalchemy_20/db.py b/sqlalchemy_20/db.py index 6793694..f4e6716 100644 --- a/sqlalchemy_20/db.py +++ b/sqlalchemy_20/db.py @@ -1,4 +1,6 @@ -from sqlalchemy import create_engine, text, insert, update, select, delete, engine_from_config, or_, and_, func, any_ +from sqlalchemy import create_engine, text, insert, update, select, delete, intersect, engine_from_config, or_, and_, \ + func, any_ +from sqlalchemy import MetaData, Table, Column, Integer, String, Enum, DATE from sqlalchemy.orm import Session, sessionmaker import configparser import sys @@ -121,10 +123,17 @@ insert_data2 = {'name': 'sql2_test2', 'password': 'pwd2'} # insert 对象方式 批量 # insert_obj2 = User(name='sql2_test8', password='pwd8') # with db_session as sess: -# # sess.bulk_save_objects([insert_obj2, insert_obj3]) +# # sess.bulk_save_objects([insert_obj2, insert_obj3]) # 推荐 # sess.add_all([insert_obj2, insert_obj3]) # sess.commit() +# insert 字典方式 批量 +# insert_dict = [{'name': 'dict1', 'password': 'dict1pwd1'}, {'name': 'dict2', 'password': 'dict2pwd2'}] +# with db_session as sess: +# sess.bulk_insert_mappings(User, insert_dict) +# sess.commit() + + # add # with db_session as sess: # user_obj = User(name='add', password='addpwd123') @@ -146,6 +155,15 @@ insert_data2 = {'name': 'sql2_test2', 'password': 'pwd2'} # for row in query_cursor.scalars(): # print(row) # row.name格式可以取到数据 +# limit +# query_cursor = db_session.execute(select(User).limit(10)) +# print(query_cursor.all()) # 数据指针,当all取过数据后one将得到None +# for row in query_cursor.scalars(): +# print(row) # row.name格式可以取到数据 + +# distinct + + # sqlalchemy1.4: session.query(User).filter_by(name='roger').all() # sql_stmt = select(User).filter_by(name='roger') # query_result = db_session.execute(sql_stmt).one() @@ -295,6 +313,54 @@ insert_data2 = {'name': 'sql2_test2', 'password': 'pwd2'} # func.random() # func.sum() + +# sqlalchemy1.4 join filter形式 +# result = session.query(User, Student).filter(User.name == Student.name).all() + +# sql_stmt = select(User, Student).where(User.name == Student.name) +# query_result = db_session.execute(sql_stmt).scalars() +# for row in query_result: +# print(row) +# print(f'{row.id}-{row.name}-{row.password}') + +# sqlalchemy1.4 join形式 无外键关联的情况 +# result = session.query(User).join(Student, User.name == Student.name).all() + +# sql_stmt = select(User).join(Student, User.name == Student.name).where(User.name.like('roger%')) +# query_result = db_session.execute(sql_stmt).scalars() +# for row in query_result: +# print(row) +# print(f'{row.id}-{row.name}-{row.password}') + +# join有外键关联的情况(Todo) + +# left_join outerjoin (Todo) + +# union +# sqlalchemy1.4 union +# q1 = session.query(User.name).filter(User.id > 1) +# q2 = session.query(Student.name).filter(Student.id <= 2) +# result = q1.union(q2).all() + +# sql_stmt1 = select(User.name).where(User.id <= 2) +# sql_stmt2 = select(Student.name).where(Student.id <= 4) +# query_result = db_session.execute(sql_stmt1.union(sql_stmt2)).scalars() +# for row in query_result: +# print(row) + +# sqlalchemy1.4 union_all +# q1 = session.query(User.id, User.name) +# q2 = session.query(Student.id.label('id'), Student.name.label('name')) +# result = q1.union_all(q2).filter(User.id <= 2) +# print(dict(result)) + +# sql_stmt1 = select(User.name).where(User.id <= 2) +# sql_stmt2 = select(Student.name).where(Student.id <= 4) +# query_result = db_session.execute(sql_stmt1.union_all(sql_stmt2)).scalars() +# for row in query_result: +# print(row) + + # select all scalars # result = db_session.execute(select(User)).scalars().all() # [<1 name:rogersun>, <2 name:honeyhoney>, <3 name:haha>] # print(result) @@ -359,3 +425,91 @@ insert_data2 = {'name': 'sql2_test2', 'password': 'pwd2'} # false 表示完全不更新 Python 中的对象 # fetch 表示重新从数据库中加载一份对象 # evaluate 表示在更新数据库的同时,也尽量在 Python 中的对象上使用同样的操作 + +# delete +# 插入测试数据 +# insert_stmt = insert(User).values([{'name': 'add', 'password': 'pwd1234'}, {'name': 'add', 'password': 'pwd1234'}]) +# insert_result = db_session.execute(insert_stmt) +# db_session.flush() +# db_session.commit() +# print(type(insert_result)) +# print(insert_result.rowcount) +# print(insert_result.is_insert) +# print(insert_result.inserted_primary_key_rows) # 2.x上返回None 这个bug会在未来版本修复 + +# inserted_primary_key_rows 可用方式 +# conn = engine.connect() +# ins = insert(User).values({'name': 'add', 'password': 'pwd1234'}) +# res = conn.execute(ins) +# print(type(res)) +# print(res.inserted_primary_key_rows) + +# 抛异常 不能使用endswith 或 like这种 只能用 == +# del_stmt = delete(User).where(and_(User.name == 'add', User.password == 'pwd1234')) +# del_result = db_session.execute(del_stmt) +# db_session.commit() +# print(type(del_result)) +# print(del_result.rowcount) + + +# 结合select的删除 +# sel_stmt = select(User.id).where(and_(User.name == 'add', User.password.endswith('1234'))) +# sel_result = db_session.execute(sel_stmt).first() +# for row in sel_result: +# print(row) +# sql_stmt = delete(User).where(User.id.in_(sel_result)) +# query_result = db_session.execute(sql_stmt) +# db_session.commit() +# print(query_result) + +# CursorResult +# all(), close(), columns(), fetchall(), fetchmany(), fetchone(), first(), freeze(), inserted_primary_key, +# inserted_primary_key_rows, is_insert, keys(), last_inserted_params(), last_updated_params(), lastrow_has_defaults(), +# lastrowid, mappings(), merge(), one(), one_or_none(), partitions(), postfetch_cols(), prefetch_cols(), +# returned_defaults, returned_defaults_rows, returns_rows, rowcount, scalar(), scalar_one(), scalar_one_or_none(), +# scalars(), splice_horizontally(), splice_vertically(), supports_sane_multi_rowcount(), supports_sane_rowcount(), +# t, tuples(), unique(), yield_per() + + +# connection +# connection = engine.connect() +# trans = connection.begin() +# try: +# ins1 = insert(User).values({'name': 'add1', 'password': 'pwd1234'}) +# ins2 = insert(User).values({'name': 'add2', 'password': 'pwd1234'}) +# connection.execute(ins1) +# connection.execute(ins2) +# trans.commit() +# except Exception as e: +# trans.rollback() +# raise e + +# 元数据表操作 + +metadata = MetaData() # 生成metadata + +user = Table( + 'user', + metadata, + Column('id', Integer, primary_key=True), + Column('name', String(32)), + Column('password', String(64)) +) + +student = Table( + 'student', + metadata, + Column('id', Integer, primary_key=True), + Column('name', String(32), nullable=False), + Column('gender', Enum('m', 'f'), nullable=False), + Column('date', DATE, nullable=False) +) + + +conn = engine.connect() +# 插入 +# ins = user.insert().values({'name': 'metadata_add1', 'password': 'pwd1234'}) +ins = insert(user).values({'name': 'metadata_add2', 'password': 'pwd1234'}) +print(str(ins)) +ins_result = conn.execute(ins) +print(ins_result.inserted_primary_key) \ No newline at end of file diff --git a/sqlalchemy_20/db_obj.py b/sqlalchemy_20/db_obj.py index 384368a..5d5af76 100644 --- a/sqlalchemy_20/db_obj.py +++ b/sqlalchemy_20/db_obj.py @@ -50,3 +50,5 @@ student = Table( Column('gender', Enum('m', 'f'), nullable=False), Column('date', DATE, nullable=False) ) + +metadata.create_all(engine)