用python在开发一个小web站点时碰到一个问题,通过mysql客户端修改库中数据后(有做提交),在前台web页面刷新还是以前的数据。而另开一个mysql客户端查询是可以查询到值的。重启web服务后可以看到新值。而同样使用java的jdbc方式连接时同样的方式是可以看到新值的。
于是决定开启mysql的日志看看实际运行的SQL有什么差异.
先看python连接方式的:
150517 13:34:00 3 Connect root@localhost on dw 3 Query SET NAMES ‘utf8‘ COLLATE ‘utf8_general_ci‘ 3 Query SET @@session.autocommit = OFF 3 Query select id,name from job where id=5 150517 13:34:20 3 Query select id,name from job where id=5 3 Quit
再来看看java的:
150517 13:39:08 5 Connect root@localhost on dw 5 Query /* mysql-connector-java-5.1.25 ( Revision: ${bzr.revision-id} ) */SHOW VARIABLES WHERE Variable_name =‘language‘ OR Variable_name = ‘ne t_write_timeout‘ OR Variable_name = ‘interactive_timeout‘ OR Variable_name = ‘wait_timeout‘ OR Variable_name = ‘character_set_client‘ OR Variable_name = ‘character_set _connection‘ OR Variable_name = ‘character_set‘ OR Variable_name = ‘character_set_server‘ OR Variable_name = ‘tx_isolation‘ OR Variable_name = ‘transaction_isolation‘ OR Variable_name = ‘character_set_results‘ OR Variable_name = ‘timezone‘ OR Variable_name = ‘time_zone‘ OR Variable_name = ‘system_time_zone‘ OR Variable_name = ‘lower _case_table_names‘ OR Variable_name = ‘max_allowed_packet‘ OR Variable_name = ‘net_buffer_length‘ OR Variable_name = ‘sql_mode‘ OR Variable_name = ‘query_cache_type‘ O R Variable_name = ‘query_cache_size‘ OR Variable_name = ‘init_connect‘ 5 Query /* mysql-connector-java-5.1.25 ( Revision: ${bzr.revision-id} ) */SELECT @@session.auto_increment_increment 5 Query SHOW COLLATION 5 Query SET NAMES latin1 5 Query SET character_set_results = NULL 5 Query SET autocommit=1 150517 13:39:09 5 Query select id,name from job where id=5 150517 13:39:29 5 Query select id,name from job where id=5 5 Quit
乍一看上去觉得差不多,没什么差异。很是苦闷,于是再想另外的方法。启动2个python脚本来尝试,一个写,另一个读。
结果发现读的那个脚本可以马上读到新增的数据。于是对比了下读的脚本发现每次读完后有做commit。把commit去掉再试,问题重现。再回过头去看了下python脚本和java脚本生成的mysql日志的差异。发现
python: 3 Query SET @@session.autocommit = OFF java: 5 Query SET autocommit=1
查询mysql的文档
The autocommit mode. If set to 1, all changes to a table take effect immediately. If set to 0, you must use COMMIT
to accept a transaction or ROLLBACK
to cancel it
autocommit=1时为自动提交即autocommit=ON.
接下来尝试了下postgresql,在autocommit=False时是可以查看到新数据的。
在看postgresql的python驱动的文档时发现有个不错的提示,转帖如下:
Warning
By default, any query execution, including a simple SELECT will start a transaction: for long-running programs, if no further action is taken, the session will remain “idle in transaction”, a condition non desiderable for several reasons (locks are held by the session, tables bloat...). For long lived scripts, either ensure to terminate a transaction as soon as possible or use an autocommit connection.
原文:http://my.oschina.net/xiangel/blog/415962