我有一个包含字段的表格oid
odate
ddate
ShippingAddr
Email
,其中oid
自动递增,我正在使用以下查询 -
"INSERT INTO order (Odate,Ddate, ShippingAddr, Email)
VALUES ('" + o.getOdate() + "','" + o.getDdate() + "','" + o.getShippingAddr() + "','" + Email + "')";
但它会提供Mysqlexception
请帮助
答案 0 :(得分:1)
根本不要像这样建立你的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();
}
这将:
请注意,我已将setDate
用于ODate
和DDate
值。我希望希望它们是数据库中的“日期”类型(或类似的东西),并且o.getODate()
返回Date
- 或者可能是Joda Time类型,例如{{ 1}}。如果您实际上只是在数据模型中使用字符串,那么另一件事就是修复(紧急,IMO)。
答案 1 :(得分:-1)
首先,您的查询易受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();