Search code examples
javasqldatejdbcprepared-statement

JDBC SQL prepared statement calling function but getting expression error


I'm trying to insert a TIMESTAMP into a table, but the timestamp inserted will always be X days away from now. Here is my code:

ps = c.prepareStatement("INSERT INTO tablename (uuid, pool, expires) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL ? DAY)");
ps.setString(1, player.getUniqueId().toString());
ps.setInt(2, plugin.s.DEFAULT_POOL);
ps.setInt(3, plugin.s.PAYMENT_DAYS);

But when this executes a syntax error occurs. If there is a better method for doing this, or a fix for this, I'd like to know. Thanks!


Solution

  • First of all note that your query is missing a closing ) at the end, the following:

    VALUES (?, ?, DATE_ADD(NOW(), INTERVAL ? DAY)
    

    Should be:

    VALUES (?, ?, DATE_ADD(NOW(), INTERVAL ? DAY))
    

    Then may be you need to use a new Date() and add to it the PAYMENT_DAYS for the date type, try the following:

    public static Date addDaysToCurrentDate(int days) {
         SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
         Calendar c = Calendar.getInstance();
         c.setTime(new Date()); 
         c.add(Calendar.DATE, days); 
         return sdf.parse(c.getTime());
    }
    
    ps = c.prepareStatement("INSERT INTO tablename (uuid, pool, expires) VALUES (?, ?, ?)");
    ps.setString(1, player.getUniqueId().toString());
    ps.setInt(2, plugin.s.DEFAULT_POOL);
    ps.setInt(3, addDaysToCurrentDate(plugin.s.PAYMENT_DAYS));