SQLalchemy rowcount เสมอ -1 สำหรับคำสั่ง
ฉันกำลังเล่นกับ SQLalchemy และ Microsoft SQL Server เพื่อหยุดฟังก์ชั่นเมื่อฉันเจอพฤติกรรมแปลก ๆ ฉันได้รับการสอนว่าแอตทริบิวต์ rowcount บนวัตถุพร็อกซีผลลัพธ์จะบอกจำนวนแถวที่ได้รับผลจากการดำเนินการคำสั่ง อย่างไรก็ตามเมื่อฉันเลือกหรือแทรกแถวเดียวหรือหลายแถวในฐานข้อมูลทดสอบของฉันฉันจะได้รับ -1 เสมอ เป็นไปได้อย่างไรและจะแก้ไขให้สะท้อนความเป็นจริงได้อย่างไร
connection = engine.connect()
metadata = MetaData()
# Ex1: select statement for all values
student = Table('student', metadata, autoload=True, autoload_with=engine)
stmt = select([student])
result_proxy = connection.execute(stmt)
results = result_proxy.fetchall()
print(result_proxy.rowcount)
# Ex2: inserting single values
stmt = insert(student).values(firstname='Severus', lastname='Snape')
result_proxy = connection.execute(stmt)
print(result_proxy.rowcout)
# Ex3: inserting multiple values
stmt = insert(student)
values_list = [{'firstname': 'Rubius', 'lastname': 'Hagrid'},
{'firstname': 'Minerva', 'lastname': 'McGonogall'}]
result_proxy = connection.execute(stmt, values_list)
print(result_proxy.rowcount)
ฟังก์ชันการพิมพ์สำหรับแต่ละบล็อกที่รันโค้ดตัวอย่างแยกกันจะพิมพ์ -1 Ex1 ดึงข้อมูลแถวทั้งหมดสำเร็จและทั้งสองคำสั่งแทรกเขียนข้อมูลไปยังฐานข้อมูลได้สำเร็จ
ตามปัญหาต่อไปนี้แอตทริบิวต์ rowcount ไม่น่าเชื่อถือเสมอไป เป็นเช่นนั้นจริงหรือ? และฉันจะชดเชยด้วยคำสั่ง Count ในธุรกรรม SQLalcehmy ได้อย่างไร? PDO :: rowCount () คืนค่า -1
คำตอบ
แถวเดียวINSERT … VALUES ( … )นั้นไม่สำคัญ: หากคำสั่งประสบความสำเร็จหนึ่งแถวจะได้รับผลกระทบและหากล้มเหลว (แสดงข้อผิดพลาด) จะมีผลต่อแถวศูนย์
สำหรับหลายแถวให้INSERTดำเนินการภายในธุรกรรมและย้อนกลับหากเกิดข้อผิดพลาด len(values_list)แล้วจำนวนแถวได้รับผลกระทบอย่างใดอย่างหนึ่งจะเป็นศูนย์หรือ
หากต้องการรับจำนวนแถวที่ SELECT จะส่งคืนให้ห่อ Select Query ในSELECT count(*)แบบสอบถามและเรียกใช้ก่อนตัวอย่างเช่น:
select_stmt = sa.select([Parent])
count_stmt = sa.select([sa.func.count(sa.text("*"))]).select_from(
select_stmt.alias("s")
)
with engine.connect() as conn:
conn.execution_options(isolation_level="SERIALIZABLE")
rows_found = conn.execute(count_stmt).scalar()
print(f"{rows_found} row(s) found")
results = conn.execute(select_stmt).fetchall()
for item in results:
print(item.id)