如何查看实际插入了多少行?
engine_str = 'mysql+mysqlconnector://root:mypass@localhost/mydb'
engine = sqlalchemy.create_engine(engine_str, echo=False, encoding='utf-8')
connection = engine.connect()
query = "INSERT INTO TEST(a,b,c)VALUES(1,2,3) ON DUPLICATE KEY UPDATE B = VALUES(B), C = VALUES(C)"
try:
connection.execute(query)
except Exception as e:
print(e)
SQLALCHEMY只打印出此ID。
<sqlalchemy.engine.result.ResultProxy object at 0x0000000007769E80>
P.S这个问题是关于行插入而不是行执行。因此,如果您使用rowcount,它将显示查询已执行的次数。
改述我的问题:有没有办法看到插入了多少记录与更新?理想情况下,我想知道那些更新的主键。
答案 0 :(得分:1)
ResultProxy.rowcount
会显示受查询影响的行数。
例如:
>> r1 = connection.execute("INSERT INTO table (id, food, is_tasty) VALUES (1, 'apple', 't'), (2, 'broccoli', 'f'), (3, 'celery', 'f')")
>> print r1.rowcount
3
这适用于其他查询:
>> r2 = connection.execute("UPDATE table SET is_tasty = 't' WHERE is_tasty = 'f'")
>> print r2.rowcount
2
>> r3 = connection.execute("DELETE FROM table WHERE food = 'celery'")
>> print r3.rowcount
1
>> r4 = connection.execute("SELECT * FROM table")
>> print r4.rowcount
2