MDB2 断开连接并在重新连接时忘记字符集设置
我们最近调试了一个奇怪的错误。 找到了解决方案,但该解决方案并不完全令人满意。
我们使用 IntSmarty 本地化我们的网站,并使用我们自己的包装器将本地化字符串存储在数据库中。 在其析构函数中,IntSmarty 保存它可能具有的任何新字符串,从而导致数据库调用。
我们使用 MDB2 的 Singleton 实例对 MySQL 进行查询,连接后我们使用 SetCharset() 函数将字符集更改为 UTF-8。 我们发现,在进行最终插入时,IntSmarty 保存的字符串被解释为 ISO-8859-1。 我们仔细查看查询日志,发现在调用IntSmarty的析构函数之前MySQL连接就断开了。 然后重新建立,但在新连接上没有发出“SET NAMES utf8”查询。 这导致保存的字符串被 MySQL 解释为 ISO-8859-1。
MDB2 上似乎没有设置默认字符集的选项。 我们对此问题的解决方案是通过添加
init-connect='SET NAMES utf8'
到 my.cnf 来更改 MySQL 服务器配置。 这只解决了我们的字符集始终相同的问题。
那么,有什么方法可以防止连接在所有查询运行之前被断开吗? 我可以在执行其他操作后强制销毁 MDB2 实例吗?
打开持久连接是可行的,但不是理想的答案。
We recently debugged a strange bug. A solution was found, but the solution is not entirely satisfactory.
We use IntSmarty to localize our website, and store the localized strings in a database using our own wrapper. In its destructor, IntSmarty saves any new strings that it might have, resulting in a database call.
We use a Singleton instance of MDB2 to do queries against MySQL, and after connecting we used the SetCharset()-function to change the character set to UTF-8. We found that strings that were saved by IntSmarty were interpreted as ISO-8859-1 when the final inserts were made. We looked closely at the query log, and found that the MySQL connection got disconnected before IntSmarty's destructor got called. It then got reestablished, but no "SET NAMES utf8" query was issued on the new connection. This resulted that the saved strings got interpreted as ISO-8859-1 by MySQL.
There seems to be no options that set the default character set on MDB2. Our solution to this problem was changing the MySQL server configuration, by adding
init-connect='SET NAMES utf8'
to my.cnf. This only solves the problem that our character set is always the same.
So, is there any way that I can prevent the connection from being torn down before all the queries have been run? Can I force the MDB2 instance to be destructed after everything else?
Turning on persistent connections works, but is not a desired answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 PHP5 文档:
(强调我的)
可能发生的情况是您的脚本没有显式销毁该对象,所以当 PHP 到达脚本末尾时,它开始按照它感觉的任何顺序清理内容 - 在您的情况下,首先关闭数据库链接。
如果您在脚本实际结束之前显式销毁 IntSmarty 对象,那么应该可以解决您的问题。
From the PHP5 documentation:
(emphasis mine)
What is probably happening is that your script does not explicitly destroy the object, and so when PHP gets to the end of the script it starts cleaning up things in whatever order it feels like--which in your case, is closing the database link first.
If you explicitly destroy the IntSmarty object prior to the actual end of the script, that should solve your problem.