我有一个人进入数据库的方法,后来用于创建人物对象:
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作为整理。
正如您所见,姓氏也会传递给该方法。
答案 0 :(得分:1)
步骤调试器和放置良好的断点或以下内容将向您显示这与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
}