Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date Java to MySql DateTime

every body. I am getting this error: 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 '14:37:41)' at line 1 for this piece of code

       public String addName() {
    // TODO Auto-generated method stub
    try {
        java.util.Date dt = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");

        String currentTime = sdf.format(dt);



        String name = "RandomName";

        Connection connect = DriverManager.getConnection(
                "jdbc:mysql://localhost", "ericman", "ericman");
        Statement stat = (Statement) connect.createStatement();
        String insert = "INSERT INTO `bookcatalog`.`puch` (`name`, `time`) VALUES ('"
                + name + "', " + currentTime + ")";
        stat.executeUpdate(insert);

    } catch (Exception e) {
        System.out.println(e);
    }
    return "Name Updated";
}

Any suggestion of why this happening, I suck on structured language just so you know :)

like image 505
helloThere Avatar asked Jan 29 '26 06:01

helloThere


1 Answers

Use PreparedStatement.

String insert = "INSERT INTO `bookcatalog`.`puch` (`name`, `time`) VALUES (?,?)";
PreparedStatement ps=connect.prepareStatement(insert);
ps.setString(1,name);
ps.setTimeStamp(2,TimeStamp.valueOf(currentTime));
ps.executeUpdate();
like image 67
KV Prajapati Avatar answered Jan 30 '26 18:01

KV Prajapati