http://d.hatena.ne.jp/end0tknr/20090403/1238753081
以前のエントリで、timestamp型のDEFAULTに関して記載しましたが、今回は update時の不思議?を記載しておきます。
尚、今回のtestでは、次のようなtableを使用します。
mysql> desc time_test; +----------+-----------+------+-----+---------------------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-----------+------+-----+---------------------+-------+ | id | int(11) | NO | PRI | NULL | | | time_val | timestamp | NO | | 0000-00-00 00:00:00 | | +----------+-----------+------+-----+---------------------+-------+ 2 rows in set (0.00 sec)
perlにおいて undef, 0 ,'' は、どれも同じような物ですが、timestamp型のupdateに使用すると、undefの場合、自動的にCURRENT_TIMESTAMPが登録されるようです。
#!/usr/local/bin/perl use strict; use warnings; use DBI; use Data::Dumper; main(); sub main { my $dbh = DBI->connect("DBI:mysql:database=test;host=localhost", "root","", {AutoCommit=> 0}); my $sql_i =<<EOF; insert into time_test (id) values(?) EOF my $sth_i = $dbh->prepare($sql_i); my $sql_u =<<EOF; update time_test set time_val=? where id=? EOF my $sth_u = $dbh->prepare($sql_u); $sth_i->execute(0); for my $id_val (([1, undef], [2, 0 ], [3, '' ] )){ $sth_i->execute($id_val->[0]); $sth_u->execute($id_val->[1],$id_val->[0]); } $dbh->commit(); $dbh->disconnect(); }
上記のscriptを実行すると、次の通り。
mysql> select * from time_test; +----+---------------------+ | id | time_val | +----+---------------------+ | 0 | 0000-00-00 00:00:00 | | 1 | 2009-07-17 22:33:47 | ←undefの場合、現在の時刻が登録される | 2 | 0000-00-00 00:00:00 | | 3 | 0000-00-00 00:00:00 | +----+---------------------+ 4 rows in set (0.00 sec)
理由は分かりませんが、不思議。