<p>在<code>MySQLdb</code>中,如果使用的是MySQL的最新版本,则不会使用<a href="http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb.converters-module.html#Thing2Literal" rel="nofollow">^{<cd2>}</a>方法,在这种情况下,当连接可用时,将使用连接的<a href="http://mysql-python.sourceforge.net/MySQLdb-1.2.2/private/_mysql-module.html#string_literal" rel="nofollow">^{<cd3>}</a>方法。在</p>
<p>您需要对<code>pymysql</code>进行修补,以便它执行相同的操作,并允许您使用连接的方法。在</p>
<h2>上下文</h2>
<p>此方法用于转义SQL语句。因此,你必须考虑安全问题。在</p>
<p>之所以要使用连接的方法是字符集,它在转义中起作用。在</p>
<h2>修复<code>ImportError</code></h2>
<p>这是一个非常简单的方法,您只需要在<a href="https://github.com/petehunt/PyMySQL/blob/master/pymysql/converters.py" rel="nofollow">^{<cd7>}</a>中实现一个伪<code>Thing2Literal</code>方法。我们永远不会叫它安威,所以我们不在乎它:</p>
<pre><code>def _Thing2Literal(o,d):
"""
Implemented for compatibility with Django.
This function is overriden by the connection's escape method when one is available.
"""
raise NotImplementedError('Thing2Literal is only implemented through the Connection object.')
Thing2Literal = _Thing2Literal
</code></pre>
<h2>当连接可用时在运行时修补<code>Thing2Literal</code></h2>
<p>在<code>pymysql.connections.Connection</code>中,添加:<code>import pymysql.converters</code></p>
<p>在<code>pymysql.connections.Connection.__init__</code>末尾,添加以下内容:</p>
^{pr2}$
<p>在<code>pymysql.connections.Connection.__del__</code>的末尾,加上反面:</p>
<pre><code>pymysql.converters.Thing2Literal = pymysql.converters._Thing2Literal
</code></pre>
<p>我们可以放弃<code>d</code>参数,因为它是现有转换的字典,<code>Connection.escape</code>方法已经可以使用它。在</p>
<h2>注意事项</h2>
<p>这很可能会被破坏,并暴露安全问题。<br/>
另外,我很确定如果你有几个活动连接使用不同的字符集,它会严重中断。在</p>
<hr/>
<p>您可能还需要对Django进行一些修改,以确保它在可用时使用您的monkey补丁版本,即用仍然将<code>Thing2Literal</code>名称绑定到模块的东西来替换{<cd15>}。在</p>
<p>当然,无需修补django并使<code>_Thing2Literal</code>函数更智能,也可以达到相同的效果。在</p>