1 package com.icl.saxon.sql; 2 import com.icl.saxon.*; 3 import com.icl.saxon.style.*; 4 import com.icl.saxon.om.NodeInfo; 5 import com.icl.saxon.expr.*; 6 import org.xml.sax.SAXException ; 7 import org.xml.sax.AttributeList ; 8 import org.w3c.dom.Node ; 9 import java.sql.*; 10 import javax.xml.transform.TransformerConfigurationException ; 12 import javax.xml.transform.TransformerException ; 13 16 17 public class SQLInsert extends StyleElement { 18 19 String table; 20 21 25 26 public boolean isInstruction() { 27 return true; 28 } 29 30 35 36 public boolean mayContainTemplateBody() { 37 return true; 38 } 39 40 public void prepareAttributes() throws TransformerConfigurationException { 41 42 table = getAttribute("table"); 43 if (table==null) reportAbsence("table"); 44 45 } 46 47 public void validate() throws TransformerConfigurationException { 48 checkWithinTemplate(); 49 } 50 51 public void process( Context context ) throws TransformerException { 52 53 55 Controller controller = context.getController(); 56 NodeInfo sourceDoc = (context.getCurrentNodeInfo()).getDocumentRoot(); 57 Connection connection = (Connection)controller.getUserData( 58 sourceDoc, "sql:connection"); 59 if (connection==null) { 60 throw styleError("No SQL connection has been established"); 61 } 62 63 PreparedStatement ps =(PreparedStatement)controller.getUserData( 64 this, "sql:statement"); 65 66 try { 67 if (ps==null) { 68 69 StringBuffer statement = new StringBuffer (); 70 statement.append("INSERT INTO " + table + " ("); 71 72 74 Node child = getFirstChild(); 75 int cols = 0; 76 while (child!=null) { 77 if (child instanceof SQLColumn) { 78 if (cols++ > 0) statement.append(','); 79 String colname = ((SQLColumn)child).getColumnName(); 80 statement.append(colname); 81 } 82 child = child.getNextSibling(); 83 } 84 statement.append(") VALUES ("); 85 86 88 for(int i=0; i<cols; i++) { 89 if (i!=0) 90 statement.append(','); 91 statement.append('?'); 92 }; 93 94 statement.append(')'); 95 96 98 ps=connection.prepareStatement(statement.toString()); 99 controller.setUserData(this, "sql:statement", ps); 100 } 101 102 104 Node child2 = getFirstChild(); 105 int i=1; 106 while (child2!=null) { 107 if (child2 instanceof SQLColumn) { 108 109 Value v = ((SQLColumn)child2).getColumnValue(context); 111 112 String val = v.asString(); 114 115 if (val.length()==1) val += " "; 117 ps.setObject(i++, val); 118 119 } 120 121 child2 = child2.getNextSibling(); 123 } 124 125 int num = ps.executeUpdate(); 126 if (!connection.getAutoCommit()) { 127 connection.commit(); 128 } 129 130 } catch (SQLException ex) { 131 throw styleError("(SQL) " + ex.getMessage()); 132 } 133 } 134 135 136 } 137 138 | Popular Tags |