【问题标题】:insert time into Mysql with java用java将时间插入Mysql
【发布时间】:2012-12-16 02:46:55
【问题描述】:

我正在为不同的客户建立一个数据库,他们有自己的用户名和密码,但我想查看他们登录的时间。我使用以下代码:

if (userName.equals("EXAMPLE")) {


                        Calendar cal = Calendar.getInstance();
                        cal.getTime();
                        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                        String Time = "update `clients` set `time`=
                          "+ sdf.format(cal.getTime()) + " where clientid=1 ";

但是它出了点问题,它没有更新表。 我将衷心感谢您的帮助。 另外,作为一个额外的问题,如果您能帮助我更新时间和日期,那就太好了。 谢谢谢谢你的时间。

【问题讨论】:

    标签: java mysql sql time


    【解决方案1】:

    我想出了答案。

    public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
    
    public static String now() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
        return sdf.format(cal.getTime());
               }
    

    然后在必要时调用 now():

    if (userName.equals("EXAMPLE")) {
    
    
                            //update time when client logged in
                            String Time = "update `clients` set `time`='" + now() + "' where clientid=1 "; 
                            stmt.executeUpdate(Time);
    
                }
    

    【讨论】:

      【解决方案2】:

      使用带参数的准备好的语句。这样您就不必格式化日期。可以保存整个日期和时间。

      看看这个链接http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html

      而且很难说为什么它没有更新,因为你没有发布任何数据库更新发生的代码。

      【讨论】:

        【解决方案3】:

        你只是在值周围缺少单引号

        String Time = "update `clients` set `time`=
                              '" + sdf.format(cal.getTime()) + "' where clientid=1 ";
        

        但请记住,这个易受攻击的 SQL Injection 使用 PreparedStatements 参数化查询

        String Time = "update `clients` set `time`= ? where clientid=1 ";
        PreparedStatement pstmt = con.prepareStatement(Time);
        pstmt.setDate(1, cal.getTime());
        pstmt.executeUpdate();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-09-11
          • 1970-01-01
          • 2011-02-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-11-20
          相关资源
          最近更新 更多