Java 日期到 MySql 日期时间
每个身体。我收到此错误: 您的 SQL 语法有错误;检查手册 对应你的MySQL服务器版本为右 第 1 行 '14:37:41)' 附近使用的语法
对于这段代码,
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";
}
任何关于为什么会发生这种情况的建议,我都会吸收结构化语言,这样你就知道:)
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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用PreparedStatement。
Use
PreparedStatement
.您在插入语句中的 currentTime 周围缺少
'
字符。然而,您确实应该使用准备好的语句来处理此类事情,以防止 SQL 注入攻击。
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.
尝试通过 str_to_date
Try convert string to date by str_to_date
您是否需要使用引号将日期/时间封装在
INSERT
语句中,就像使用 name 参数一样?Do you need to encapsulate the date/time in your
INSERT
statement with inverted commas, like you do with the name argument?啊。为什么不使用PreparedStatement 来代替呢?
它干净得多。
ugh. Why don't you use a PreparedStatement instead?
It's far cleaner.