Reputation: 1591
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 :)
Upvotes: 2
Views: 5574
Reputation: 11638
ugh. Why don't you use a PreparedStatement instead?
PreparedStatement stmt = connect.prepareStatement("INSERT INTO bookcatalog.puch(name, time) values ?,?");
stmt.setString(1, name);
stmt.setTimestamp(2, dt);
stmt.execute();
It's far cleaner.
Upvotes: 1
Reputation: 1924
Do you need to encapsulate the date/time in your INSERT
statement with inverted commas, like you do with the name argument?
Upvotes: 1
Reputation: 41767
You are missing '
characters around your currentTime in the insert statement.
However, you really should be using a prepared statement for such things, to guard against SQL injection attacks.
Upvotes: 3
Reputation: 94653
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();
Upvotes: 6