将时间戳插入shell中的mysql列

时间:2013-01-31 23:38:53

标签: mysql linux bash shell unix

以下适用于我:

mysql -u 'root' -h 8.8.8.88 mo -e 'UPDATE `path_last_updated` 
    SET timestamp="2012-01-03 00:00:00"'

但是,以下情况并非如此:

TIMESTAMP=`date "+%Y-%m-%d-%T"`
mysql -u 'root' -h 8.8.8.88 mo -e 'UPDATE `path_last_updated` 
    SET timestamp=$TIMESTAMP'

如何将unix中的时间戳插入我的mysql表?

更新

TIMESTAMP=`date "+%Y-%m-%d %T"`
mysql -u 'root' -h 8.8.8.88 mo -e "UPDATE `path_last_updated` 
    SET timestamp='$TIMESTAMP'"

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual 
that corresponds to your MySQL server version for the right syntax to use near 'SET 
timestamp='2013-01-31 15:46:00'' at line 1

2 个答案:

答案 0 :(得分:2)

Shell变量插值only works between double quotes ("), not single (')。你也有反引号,在双引号字符串中将被视为嵌入式shell命令。

尝试:

mysql -u 'root' -h 8.8.8.88 mo -e "UPDATE \`path_last_updated\`
    SET timestamp='$TIMESTAMP'"

另外,fwiw,你在日期命令的格式中有一个额外的短划线( - ),在%d和%T之间。

答案 1 :(得分:0)

ALTER TABLE让它变得更容易:

ALTER TABLE path_last_updated ADD date_entered timestamp DEFAULT CURRENT_TIMESTAMP

然后在shell中:

mysql -u 'root' -h 8.8.8.88 mo -e "UPDATE path_last_updated SET timestamp=DEFAULT"