SQL类型说明符

时间:2017-03-29 11:46:03

标签: java sql jdbc

大家好我们有问题,不知道如何为日期类型添加类型说明符?我们尝试使用%%,但这似乎不起作用。

    public class OrderDB implements OrderDBIF {
@Override
public Order create(Date date, int totalAmount, String deliveryStatus, Date deliveryDate, int invoiceId, int customerId) throws SQLException {
    String sql = String.format("INSERT INTO Order (date, totalAmount, deliveryStatus, deliveryDate, invoiceId, customerId) VALUES "
            + "('%%', '%d', '%s', '%%', '%d', '%d')", date, totalAmount, deliveryStatus, deliveryDate, invoiceId, customerId);
    try (Connection conn = DBConnection.getInstance().getDBcon();
         Statement stmt = conn.createStatement()) {
        stmt.executeUpdate(sql);
    } catch(SQLException e) {
        e.printStackTrace();
        throw e;
    }

1 个答案:

答案 0 :(得分:3)

使用预先准备好的声明:

String sql = "INSERT INTO Order "
    + "(date, totalAmount, deliveryStatus, deliveryDate, invoiceId, customerId) VALUES "
    + "(?,?,?,?,?,?)";
try (Connection conn = DBConnection.getInstance().getDBcon();
    PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setDate(1, date);
    ps.setInt(2, totalAmount);
    ps.setString(3, deliveryStatus);
    ps.setDate(4, deliveryDate);
    ps.setInt(5, invoiceId);
    ps.setInt(6, customerId);
    ps.executeUpdate();
} catch(SQLException e) {
    e.printStackTrace();
    throw e;
}

除了对INSERT中的所有值进行适当的转义外,预准备语句还可以保护您免受SQL注入。