1 package ca.spaz.sql; 2 3 import java.sql.*; 4 5 import org.apache.log4j.Logger; 6 7 /*** 8 * Simplifies constructing SQL Insert Queries. 9 * 10 * @author davidson 11 */ 12 public class SQLInsert extends SQLStatement implements Columns { 13 /*** 14 * Logger for this class 15 */ 16 private static final Logger logger = Logger.getLogger(SQLInsert.class); 17 18 private SQLColumnSet cols; 19 20 public SQLInsert(String tableName) { 21 super(tableName, true, true); 22 cols = new SQLColumnSet(); 23 } 24 25 protected void doExecute(Connection con) throws SQLException { 26 Statement stmt = con.createStatement(); 27 String query = this.getQueryString(); 28 if (logger.isDebugEnabled()) { 29 logger.debug("executeQuery() - Statement to be executed: " + query); 30 } 31 32 stmt.execute(query); 33 } 34 35 protected ResultSet doExecuteQuery(Connection con) throws SQLException { 36 Statement stmt = con.createStatement(); 37 String query = this.getQueryString(); 38 if (logger.isDebugEnabled()) { 39 logger.debug("executeQuery() - Statement to be executed: " + query); 40 } 41 42 stmt.executeUpdate(query); 43 if (con.getMetaData().supportsGetGeneratedKeys()) { 44 return stmt.getGeneratedKeys(); 45 } else { 46 return null; 47 } 48 } 49 50 51 protected String getQueryString() { 52 StringBuffer sb = new StringBuffer(); 53 sb.append("INSERT INTO "); 54 sb.append(this.table); 55 56 sb.append(cols.getNameString()); 57 58 sb.append("\n VALUES "); 59 sb.append(cols.getValueString()); 60 sb.append(";"); 61 return sb.toString(); 62 } 63 64 /*** 65 * Retrieve the <code>cols</code> from the <code>SQLInsert</code> 66 * @return Returns the cols. 67 */ 68 public SQLColumnSet getColumns() { 69 return cols; 70 } 71 72 }