Statement stmt;
String sql;
int rows;
sql = "INSERT INTO tCust "
+ "(custId, custName, custAddr) "
+ "VALUES "
+ "('" + custId + "',"
+ "('" + custName + "',"
+ "('" + custAddr + "')";
stmt = theConn.createStatement();
rows = stmt.executeUpdate(sql);
theConn.dbConn.commit();
stmt.close();Thanks to Lawrence Angrave for the warning.
public class StringUtils {
public static void main(String args[]) {
System.out.println(StringUtils.sqlQuote("Real's HowTo"));
System.out.println(StringUtils.sqlQuote("HowTo"));
System.out.println(StringUtils.sqlQuote(""));
System.out.println(StringUtils.sqlQuote("Real's HowTo's"));
System.out.println(StringUtils.sqlQuote("'"));
System.out.println(StringUtils.sqlQuote("''"));
/*
output:
Real''s HowTo
HowTo
Real''s HowTo''s
''
''''
*/
}
public static String sqlQuote(String str) {
if(str == null || str.length() == 0 || str.indexOf("\'") == -1){
return str;
}
StringBuffer sb = new StringBuffer();
for(int i = 0; i < str.length(); i++){
sb.append(str.charAt(i));
if(str.charAt(i)=='\'') sb.append('\'')
}
return sb.toString();
}
}
Or use a PreparedStatement to insert data containing QUOTES.
PreparedStatement stmt = null;
String sql;
int rows;
try {
sql = "INSERT INTO tCust"
+ "(custName) "
+ "VALUES "
+ "(?)";
stmt = theConn.prepareStatement(sql);
stmt.setString(1, "Name with ' are permitted!");
rows = stmt.executeUpdate();
stmt.close();
}
catch (Exception e){
e.printStackTrace();
}
The character "\" (backslash) can be difficult to use in an INSERT statement since "\" is considered as an escape character in Java (and probably by the database too).
stmt.executeUpdate("INSERT INTO mytable VALUES('\\')");
stmt.executeUpdate("INSERT INTO mytable VALUES('\\\\')");
Written and compiled by Réal Gagnon ©1998-2012
[ home ]