Java 插入包含日期的查询格式
我有一份由feilds odate ddate ShippingAddr电子邮件组成的表格订单 ,其中oid是自动递增的,我使用以下查询-Java 插入包含日期的查询格式,java,mysql,Java,Mysql,我有一份由feilds odate ddate ShippingAddr电子邮件组成的表格订单 ,其中oid是自动递增的,我使用以下查询- "INSERT INTO order (Odate,Ddate, ShippingAddr, Email) VALUES ('" + o.getOdate() + "','" + o.getDdate() + "','" + o.getShippingAddr() + "','" + Email + "')"; 但是它给出了一个Mysqlexcepti
"INSERT INTO order (Odate,Ddate, ShippingAddr, Email)
VALUES ('" + o.getOdate() + "','" + o.getDdate() + "','" + o.getShippingAddr() + "','" + Email + "')";
但是它给出了一个Mysqlexception,请帮助首先,您的查询易受SQL注入攻击。所以我建议你使用事先准备好的陈述 order是SQL的保留字。对于MySQL,如果要将保留字用作表名或字段名,则应引用保留字
Connection c= null;
PreparedStatement ps= null;
c = setTheDBConnection(); //just for example
ps = c.preparedStatement("INSERT INTO `order` (Odate,Ddate,ShippingAddr,Email) VALUES (?,?,?,?)");
ps.setString(1, o.getOdate());
ps.setString(2, o.getDdate());
ps.setString(3, o.getShippingAddr());
ps.setString(4, Email);
ps.executeUpdate();
不要像这样构建SQL。而是使用参数化SQL,并设置各种参数值
// You still need to escape the "order" table name as per Özkan's answer
String sql =
"INSERT INTO `order` (ODate, DDate, ShippingAddr, Email) VALUES (?, ?, ?, ?)";
try (PreparedStatement pst = conn.prepareStatement(sql))
{
pst.setDate(1, o.getOdate());
pst.setDate(2, o.getDdate());
pst.setString(3, o.getShippingAddr());
pst.setString(4, Email);
pst.executeUpdate();
}
这将:
避免
当问题出在SQL上时,当问题出在数据上时,问题中的SQL问题实际上不是日期问题,但它们最终混淆了问题
将代码与数据分开
避免日期等转换问题
请注意,我对ODate和DDate值使用了setDate。我希望它们是数据库中的日期类型或类似类型,并且o.getODate返回一个日期,或者可能是一个Joda时间类型,比如LocalDate。如果您实际上只是对数据模型中的所有内容使用字符串,我想这是另一件需要紧急解决的事情。不,不要这样做。这是一个等待发生的SQL注入攻击。@JonSkeet我刚才指出了错误发生的原因。我现在不关心SQL注入。不管上下文如何,SQL注入漏洞都是坏的。声称他们不是你的责任是,嗯……不负责任。@ÖzkanÖZLÜ:然而,我认为在任何地方指出这一点都很重要。OP没有提到他是在使用语句还是preparedstatement。这个答案正是根据你如何执行这个查询的问题得出的?向我们展示正在积极使用此字符串的部分。