我有以下方法将一个人放入数据库,该数据库随后用于创建一个人对象:

public static void addPerson(String personCode, String firstName, String lastName,
        String phoneNo, String street, String city, String state,
        String zip, String country) {
    Connection conn = database.com.airamerica.interfaces.DatabaseConnect.getConnection();
    PreparedStatement ps;
    ResultSet rs;
    String addAddressQuery = "INSERT INTO `Addresses` (`street`,`city`,`state`,`zip`,`country`) VALUES (?,?,?,?,?)";
    String checkAddress = "SELECT `address_ID` FROM `Addresses` WHERE street = ? AND city = ? AND state = ? AND zip = ? AND country = ?";
    String addPersonQuery = "INSERT INTO `Persons` (`personCode`,`firstName`,`lastName`,`address_ID`,`phoneNumber`) VALUES (?,?,?,(SELECT `address_ID` FROM `Addresses` WHERE street = ? AND city = ? AND state = ? AND zip = ? AND country = ?),?)";
    try
    {
        ps = conn.prepareStatement(checkAddress);
        ps.setString(1, street);
        ps.setString(2, city);
        ps.setString(3, state);
        ps.setString(4, zip);
        ps.setString(5, country);
        rs = ps.executeQuery();
        if(!(rs.next())){
            ps = conn.prepareStatement(addAddressQuery);
            ps.setString(1, street);
            ps.setString(2, city);
            ps.setString(3, state);
            ps.setString(4, zip);
            ps.setString(5, country);
            ps.executeUpdate();
            ps.close();
        }
        ps.close();
        rs.close();
        ps = conn.prepareStatement(addPersonQuery);
        ps.setString(1, personCode);
        ps.setString(2, firstName);
        ps.setString(3, lastName);
        ps.setString(4, street);
        ps.setString(5, city);
        ps.setString(6, state);
        ps.setString(7, zip);
        ps.setString(8, country);
        ps.setString(9, phoneNo);
        ps.executeUpdate();
        ps.close();
        conn.close();
    }
    catch (SQLException e)
    {
        System.out.println("SQLException: ");
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}


问题是当我们插入像Miles O'Brien这样的名称时,它被插入为Miles O'Brien时,我试图使用一种方法来转义,以使用其中的两个('')替换单引号(撇号)以进行转义。该方法只是导致将数据作为Miles O''Brien插入。我们如何解决这个问题?问题出在ps.setString(3, lastName);上,如何不将姓氏作为'输入到数据库中?

万一您需要它,引擎是InnoDB,我们使用默认的UTF8作为排序规则。

如您所见,姓氏也传递给该方法。

最佳答案

GIGO

步骤调试器和适当放置的断点或以下内容将向您表明这与JDBC根本无关。

逐步调试器是检查正在运行的代码的首选方法!

public static void addPerson(final String personCode, final String firstName, final String lastName,
                             final String phoneNo, final String street, final String city, final String state,
                             final String zip, final String country) {

        System.out.println(String.format("Last Name = %s",lastName));

        // the rest of your code
}

10-08 11:10