1 package ca.spaz.sql; 2 3 import java.sql.*; 4 import java.util.*; 5 6 import org.apache.log4j.Logger; 7 8 /*** 9 * Simplifies constructing SQL Update Queries. 10 */ 11 public class SQLUpdate extends SQLSelectableStatement implements Columns { 12 /*** 13 * Logger for this class 14 */ 15 private static final Logger logger = Logger.getLogger(SQLUpdate.class); 16 17 private SQLColumnSet cols; 18 19 /*** 20 * Create a new SQLUpdate command for the given table 21 * @param tableName the name of the table to update on 22 */ 23 public SQLUpdate(String tableName) { 24 super(tableName, true, false, true); 25 cols = new SQLColumnSet(); 26 } 27 28 /*** 29 * Overrides execute() and calls executeUpdate() 30 */ 31 protected void doExecute(Connection con) throws SQLException { 32 Statement stmt = con.createStatement(); 33 String query = this.getQueryString(); 34 if (logger.isDebugEnabled()) { 35 logger.debug("executeQuery() - Statement to be executed: " + query); 36 } 37 38 stmt.executeUpdate(query); 39 } 40 41 /*** 42 * Generate the SQL string for an UPDATE command. 43 */ 44 protected String getQueryString() { 45 StringBuffer sb = new StringBuffer(); 46 sb.append("UPDATE "); 47 sb.append(getTableName()); 48 sb.append(" SET "); 49 List names = cols.getNames(); 50 List terms = cols.getValues(); 51 for (int i=0; i<names.size(); i++) { 52 Object name = names.get(i); 53 Object term = terms.get(i); 54 if (term == null) { 55 term = "NULL"; 56 } 57 sb.append(name.toString()); 58 sb.append(" = '"); 59 sb.append(escape(term.toString())); 60 sb.append("' "); 61 if (i < names.size() - 1) { 62 sb.append(", "); 63 } 64 } 65 sb.append(getWhere()); 66 return sb.toString(); 67 } 68 69 /*** 70 * Retrieve the <code>cols</code> from the <code>SQLInsert</code> 71 * @return Returns the cols. 72 */ 73 public SQLColumnSet getColumns() { 74 return cols; 75 } 76 77 }