擅长:python、mysql、java
<p>我不确定pyodbc——我想这取决于您连接到哪个特定的数据库引擎。不幸的是,许多实现DB API 2.0的模块似乎没有在文档中指定事务是特定于连接还是游标,dbapi2.0本身的规范也没有(<a href="http://legacy.python.org/dev/peps/pep-0249/" rel="nofollow">http://legacy.python.org/dev/peps/pep-0249/</a>)</p>
<p>但是,有几个数据库中的事务包括所有游标在单个连接上执行的所有语句(这意味着您的第一个和第二个示例都可以工作)。例如,psycopg2文档明确声明了以下内容:</p>
<blockquote>
<p>[D]atabase commands will be executed in the context of the same
transaction – not only the commands issued by the first cursor, but
the ones issued by all the cursors created by the same connection.</p>
</blockquote>
<p>(在<a href="http://initd.org/psycopg/docs/usage.html" rel="nofollow">http://initd.org/psycopg/docs/usage.html</a>中的“事务控制”下)</p>
<p>类似地,MySQL不支持游标——它们在模块中的Python级别进行模拟——因此根据定义,事务封装了整个连接级别,而不仅仅是单个游标。</p>