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 static String convertString(String source) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < source.length(); i++){
sb.append(source.charAt(i));
if(source.charAt(i)=='\'') sb.append('\'')
}
return sb.toString();
}Or you can 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();
theConn.commit();
stmt.close();
System.out.println(sql);
}
catch (Exception e){
e.printStackTrace();
}The character "\" can be difficult to use in an INSERT statement since "\" is considered as an escape character in Java (and probably by the database also).
stmt.executeUpdate("INSERT INTO mytable VALUES('\\')");
stmt.executeUpdate("INSERT INTO mytable VALUES('\\\\')");
Written and compiled by Réal Gagnon ©1998-2005
[ home ]