<p>连接具有PEP-249(Python数据库API规范v2.0)中指定的<a href="https://www.python.org/dev/peps/pep-0249/#connection-close" rel="noreferrer">^{<cd1>}</a>方法:</p>
<pre><code>import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
csr = conn.cursor()
csr.close()
conn.close() #<--- Close the connection
</code></pre>
<hr/>
<p>由于<code>pyodbc</code><a href="https://github.com/mkleehammer/pyodbc/wiki/Connection#connection-objects-and-the-python-context-manager-syntax" rel="noreferrer">connection</a>和<a href="https://github.com/mkleehammer/pyodbc/wiki/Cursor#cursor-objects-and-the-python-context-manager-syntax" rel="noreferrer">cursor</a>都是上下文管理器,现在将其编写为:</p>
<pre><code>import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
with conn:
crs = conn.cursor()
do_stuff
# conn.commit() will automatically be called when Python leaves the outer `with` statement
# Neither crs.close() nor conn.close() will be called upon leaving the the `with` statement!!
</code></pre>
<p>有关为何不调用conn.close()的解释,请参见<a href="https://github.com/mkleehammer/pyodbc/issues/43" rel="noreferrer">https://github.com/mkleehammer/pyodbc/issues/43</a>。</p>
<p>注意,与原始代码不同,这会导致调用<code>conn.commit()</code>。使用外部<code>with</code>语句控制何时要调用<code>commit</code>。</p>
<hr/>
<p>还要注意,无论是否使用<code>with</code>语句,每个<a href="https://github.com/mkleehammer/pyodbc/wiki/Connection#close" rel="noreferrer">the docs</a></p>
<blockquote>
<p>Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [<code>conn.close()</code>], but you can explicitly close the connection if you wish.</p>
</blockquote>
<p>同样地<a href="https://github.com/mkleehammer/pyodbc/wiki/Cursor#close" rel="noreferrer">for cursors</a>(我的重点是):</p>
<blockquote>
<p>Cursors are closed automatically when they are deleted (typically when they go out of scope), <em>so calling [<code>csr.close()</code>] is not usually necessary</em>.</p>
</blockquote>