Question

I´m sending to server string sysdate()from an android device. The problem is that the code doesnt insert anything to mysql database. The column first is DATETIME. I´m using mysql workbench, when i type INSERT INTO test (first) VALUES (sysdate()); in the workbench, it works.

<%
     String t = request.getParameter("time");
            Connection connection = null;
            PreparedStatement pstatement = null;
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            int updateQuery = 0;
            if (t != null) {
                if (t != "" ) {
                    try {
                        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
                        Statement st = connection.createStatement();
                        String queryString1 = "INSERT INTO test (first) VALUES (?)";
                        pstatement = connection.prepareStatement(queryString1);
                        pstatement.setString(1, t);
                        updateQuery = pstatement.executeUpdate();
                        if (updateQuery != 0) {
                            response.setStatus(400);
                        }
                    } catch (Exception ex) {
                        out.println(ex);

                    } finally {
                        pstatement.close();
                        connection.close();
                    }
                } 
            } 
        %>
Was it helpful?

Solution

My Java is very rusty, but nobody else has jumped in so I'll give this a try. I remember dates being tricky with JDBC.

Here are two attempts, but be warned that they're untested because I don't have the setup right now to test them.

Approach #1: pass the date as a string and have MySQL convert it. Instead of this for your INSERT statement:

String queryString1 = "INSERT INTO test (first) VALUES (?)";

... try this:

String queryString1 = "INSERT INTO test (first) VALUES (str_to_date(?, '%Y-%m-%d %H:%i:%s'))";

Approach #2: use PreparedStatement.setDate instead of PreparedStatement.setString. Note that this uses your original INSERT statement, not the one proposed in Approach 1. This means converting the string date t to a java.util.Date and then to a java.sql.date.

Instead of this for your set:

pstatement.setString(1, t);

... try this:

// Change string to java.util.Date
java.util.Date dt = new java.text.SimpleDateFormat(
    "yyyy-MM-dd HH:mm:ss", java.util.Locale.ENGLISH).parse(t);

// Change java.util.Date to java.sql.Date
java.sql.Date sqlDt = new java.sql.Date(dt.getTime());

// Set parameter as a date
pstatement.setDate(1, sqlDt);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top