List of usage examples for java.sql PreparedStatement setDouble
void setDouble(int parameterIndex, double x) throws SQLException;
double
value. From source file:org.apache.ddlutils.platform.PlatformImplBase.java
/** * This is the core method to set the parameter of a prepared statement to a given value. * The primary purpose of this method is to call the appropriate method on the statement, * and to give database-specific implementations the ability to change this behavior. * //from w w w. j av a 2 s . c om * @param statement The statement * @param sqlIndex The parameter index * @param typeCode The JDBC type code * @param value The value * @throws SQLException If an error occurred while setting the parameter value */ protected void setStatementParameterValue(PreparedStatement statement, int sqlIndex, int typeCode, Object value) throws SQLException { if (value == null) { statement.setNull(sqlIndex, typeCode); } else if (value instanceof String) { statement.setString(sqlIndex, (String) value); } else if (value instanceof byte[]) { statement.setBytes(sqlIndex, (byte[]) value); } else if (value instanceof Boolean) { statement.setBoolean(sqlIndex, ((Boolean) value).booleanValue()); } else if (value instanceof Byte) { statement.setByte(sqlIndex, ((Byte) value).byteValue()); } else if (value instanceof Short) { statement.setShort(sqlIndex, ((Short) value).shortValue()); } else if (value instanceof Integer) { statement.setInt(sqlIndex, ((Integer) value).intValue()); } else if (value instanceof Long) { statement.setLong(sqlIndex, ((Long) value).longValue()); } else if (value instanceof BigDecimal) { // setObject assumes a scale of 0, so we rather use the typed setter statement.setBigDecimal(sqlIndex, (BigDecimal) value); } else if (value instanceof Float) { statement.setFloat(sqlIndex, ((Float) value).floatValue()); } else if (value instanceof Double) { statement.setDouble(sqlIndex, ((Double) value).doubleValue()); } else { statement.setObject(sqlIndex, value, typeCode); } }
From source file:org.LexGrid.util.sql.lgTables.SQLTableUtilities.java
/** * Runs SQL Statement "INSERT" on the given table and and table prefix for * the supplied attributeValues// w w w. j av a2 s.c o m * * @param table * @param attributeValues * @return * @throws SQLException */ public boolean insertRow(String table, Map attributeValues) throws SQLException { PreparedStatement prepStmt = null; Object attribute = null; boolean success = false; try { prepStmt = sqlConnection_.prepareStatement(getSQLTableConstants().getInsertStatementSQL(table)); for (int i = 0; i < attributeValues.size(); i++) { attribute = attributeValues.get("" + (i + 1)); // If null, we are unable to determine the SQL param type, // so String is assumed by default. if (attribute == null) { prepStmt.setString(i + 1, null); } else if (attribute instanceof String) { prepStmt.setString(i + 1, (String) attribute); } else if (attribute instanceof Blob) { prepStmt.setBlob(i + 1, (Blob) attribute); } else if (attribute instanceof Boolean) { prepStmt.setBoolean(i + 1, ((Boolean) attribute).booleanValue()); } else if (attribute instanceof Byte) { prepStmt.setByte(i + 1, ((Byte) attribute).byteValue()); } else if (attribute instanceof byte[]) { prepStmt.setBytes(i + 1, (byte[]) attribute); } else if (attribute instanceof Date) { prepStmt.setDate(i + 1, (Date) attribute); } else if (attribute instanceof Double) { prepStmt.setDouble(i + 1, ((Double) attribute).doubleValue()); } else if (attribute instanceof Float) { prepStmt.setFloat(i + 1, ((Float) attribute).floatValue()); } else if (attribute instanceof Integer) { prepStmt.setInt(i + 1, ((Integer) attribute).intValue()); } else if (attribute instanceof Long) { prepStmt.setLong(i + 1, ((Long) attribute).longValue()); } else if (attribute instanceof Short) { prepStmt.setShort(i + 1, ((Short) attribute).shortValue()); } else if (attribute instanceof Timestamp) { prepStmt.setTimestamp(i + 1, (Timestamp) attribute); } } success = prepStmt.execute(); } finally { prepStmt.close(); } return success; }
From source file:com.flexive.core.storage.GenericDivisionImporter.java
/** * Import data from a zip archive to a database table * * @param stmt statement to use * @param zip zip archive containing the zip entry * @param ze zip entry within the archive * @param xpath xpath containing the entries to import * @param table name of the table * @param executeInsertPhase execute the insert phase? * @param executeUpdatePhase execute the update phase? * @param updateColumns columns that should be set to <code>null</code> in a first pass (insert) * and updated to the provided values in a second pass (update), * columns that should be used in the where clause have to be prefixed * with "KEY:", to assign a default value use the expression "columnname:default value", * if the default value is "@", it will be a negative counter starting at 0, decreasing. * If the default value starts with "%", it will be set to the column following the "%" * character in the first pass * @throws Exception on errors//from w w w . ja v a 2 s. co m */ protected void importTable(Statement stmt, final ZipFile zip, final ZipEntry ze, final String xpath, final String table, final boolean executeInsertPhase, final boolean executeUpdatePhase, final String... updateColumns) throws Exception { //analyze the table final ResultSet rs = stmt.executeQuery("SELECT * FROM " + table + " WHERE 1=2"); StringBuilder sbInsert = new StringBuilder(500); StringBuilder sbUpdate = updateColumns.length > 0 ? new StringBuilder(500) : null; if (rs == null) throw new IllegalArgumentException("Can not analyze table [" + table + "]!"); sbInsert.append("INSERT INTO ").append(table).append(" ("); final ResultSetMetaData md = rs.getMetaData(); final Map<String, ColumnInfo> updateClauseColumns = updateColumns.length > 0 ? new HashMap<String, ColumnInfo>(md.getColumnCount()) : null; final Map<String, ColumnInfo> updateSetColumns = updateColumns.length > 0 ? new LinkedHashMap<String, ColumnInfo>(md.getColumnCount()) : null; final Map<String, String> presetColumns = updateColumns.length > 0 ? new HashMap<String, String>(10) : null; //preset to a referenced column (%column syntax) final Map<String, String> presetRefColumns = updateColumns.length > 0 ? new HashMap<String, String>(10) : null; final Map<String, Integer> counters = updateColumns.length > 0 ? new HashMap<String, Integer>(10) : null; final Map<String, ColumnInfo> insertColumns = new HashMap<String, ColumnInfo>( md.getColumnCount() + (counters != null ? counters.size() : 0)); int insertIndex = 1; int updateSetIndex = 1; int updateClauseIndex = 1; boolean first = true; for (int i = 0; i < md.getColumnCount(); i++) { final String currCol = md.getColumnName(i + 1).toLowerCase(); if (updateColumns.length > 0) { boolean abort = false; for (String col : updateColumns) { if (col.indexOf(':') > 0 && !col.startsWith("KEY:")) { String value = col.substring(col.indexOf(':') + 1); col = col.substring(0, col.indexOf(':')); if ("@".equals(value)) { if (currCol.equalsIgnoreCase(col)) { counters.put(col, 0); insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++)); sbInsert.append(',').append(currCol); } } else if (value.startsWith("%")) { if (currCol.equalsIgnoreCase(col)) { presetRefColumns.put(col, value.substring(1)); insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++)); sbInsert.append(',').append(currCol); // System.out.println("==> adding presetRefColumn "+col+" with value of "+value.substring(1)); } } else if (!presetColumns.containsKey(col)) presetColumns.put(col, value); } if (currCol.equalsIgnoreCase(col)) { abort = true; updateSetColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), updateSetIndex++)); break; } } if (abort) continue; } if (first) { first = false; } else sbInsert.append(','); sbInsert.append(currCol); insertColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), insertIndex++)); } if (updateColumns.length > 0 && executeUpdatePhase) { sbUpdate.append("UPDATE ").append(table).append(" SET "); int counter = 0; for (String updateColumn : updateSetColumns.keySet()) { if (counter++ > 0) sbUpdate.append(','); sbUpdate.append(updateColumn).append("=?"); } sbUpdate.append(" WHERE "); boolean hasKeyColumn = false; for (String col : updateColumns) { if (!col.startsWith("KEY:")) continue; hasKeyColumn = true; String keyCol = col.substring(4); for (int i = 0; i < md.getColumnCount(); i++) { if (!md.getColumnName(i + 1).equalsIgnoreCase(keyCol)) continue; updateClauseColumns.put(keyCol, new ColumnInfo(md.getColumnType(i + 1), updateClauseIndex++)); sbUpdate.append(keyCol).append("=? AND "); break; } } if (!hasKeyColumn) throw new IllegalArgumentException("Update columns require a KEY!"); sbUpdate.delete(sbUpdate.length() - 5, sbUpdate.length()); //remove trailing " AND " //"shift" clause indices for (String col : updateClauseColumns.keySet()) { GenericDivisionImporter.ColumnInfo ci = updateClauseColumns.get(col); ci.index += (updateSetIndex - 1); } } if (presetColumns != null) { for (String key : presetColumns.keySet()) sbInsert.append(',').append(key); } sbInsert.append(")VALUES("); for (int i = 0; i < insertColumns.size(); i++) { if (i > 0) sbInsert.append(','); sbInsert.append('?'); } if (presetColumns != null) { for (String key : presetColumns.keySet()) sbInsert.append(',').append(presetColumns.get(key)); } sbInsert.append(')'); if (DBG) { LOG.info("Insert statement:\n" + sbInsert.toString()); if (updateColumns.length > 0) LOG.info("Update statement:\n" + sbUpdate.toString()); } //build a map containing all nodes that require attributes //this allows for matching simple xpath queries like "flatstorages/storage[@name='FX_FLAT_STORAGE']/data" final Map<String, List<String>> queryAttributes = new HashMap<String, List<String>>(5); for (String pElem : xpath.split("/")) { if (!(pElem.indexOf('@') > 0 && pElem.indexOf('[') > 0)) continue; List<String> att = new ArrayList<String>(5); for (String pAtt : pElem.split("@")) { if (!(pAtt.indexOf('=') > 0)) continue; att.add(pAtt.substring(0, pAtt.indexOf('='))); } queryAttributes.put(pElem.substring(0, pElem.indexOf('[')), att); } final PreparedStatement psInsert = stmt.getConnection().prepareStatement(sbInsert.toString()); final PreparedStatement psUpdate = updateColumns.length > 0 && executeUpdatePhase ? stmt.getConnection().prepareStatement(sbUpdate.toString()) : null; try { final SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); final DefaultHandler handler = new DefaultHandler() { private String currentElement = null; private Map<String, String> data = new HashMap<String, String>(10); private StringBuilder sbData = new StringBuilder(10000); boolean inTag = false; boolean inElement = false; int counter; List<String> path = new ArrayList<String>(10); StringBuilder currPath = new StringBuilder(100); boolean insertMode = true; /** * {@inheritDoc} */ @Override public void startDocument() throws SAXException { counter = 0; inTag = false; inElement = false; path.clear(); currPath.setLength(0); sbData.setLength(0); data.clear(); currentElement = null; } /** * {@inheritDoc} */ @Override public void processingInstruction(String target, String data) throws SAXException { if (target != null && target.startsWith("fx_")) { if (target.equals("fx_mode")) insertMode = "insert".equals(data); } else super.processingInstruction(target, data); } /** * {@inheritDoc} */ @Override public void endDocument() throws SAXException { if (insertMode) LOG.info("Imported [" + counter + "] entries into [" + table + "] for xpath [" + xpath + "]"); else LOG.info("Updated [" + counter + "] entries in [" + table + "] for xpath [" + xpath + "]"); } /** * {@inheritDoc} */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { pushPath(qName, attributes); if (currPath.toString().equals(xpath)) { inTag = true; data.clear(); for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getLocalName(i); if (StringUtils.isEmpty(name)) name = attributes.getQName(i); data.put(name, attributes.getValue(i)); } } else { currentElement = qName; } inElement = true; sbData.setLength(0); } /** * Push a path element from the stack * * @param qName element name to push * @param att attributes */ private void pushPath(String qName, Attributes att) { if (att.getLength() > 0 && queryAttributes.containsKey(qName)) { String curr = qName + "["; boolean first = true; final List<String> attList = queryAttributes.get(qName); for (int i = 0; i < att.getLength(); i++) { if (!attList.contains(att.getQName(i))) continue; if (first) first = false; else curr += ','; curr += "@" + att.getQName(i) + "='" + att.getValue(i) + "'"; } curr += ']'; path.add(curr); } else path.add(qName); buildPath(); } /** * Pop the top path element from the stack */ private void popPath() { path.remove(path.size() - 1); buildPath(); } /** * Rebuild the current path */ private synchronized void buildPath() { currPath.setLength(0); for (String s : path) currPath.append(s).append('/'); if (currPath.length() > 1) currPath.delete(currPath.length() - 1, currPath.length()); // System.out.println("currPath: " + currPath); } /** * {@inheritDoc} */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (currPath.toString().equals(xpath)) { if (DBG) LOG.info("Insert [" + xpath + "]: [" + data + "]"); inTag = false; try { if (insertMode) { if (executeInsertPhase) { processColumnSet(insertColumns, psInsert); counter += psInsert.executeUpdate(); } } else { if (executeUpdatePhase) { if (processColumnSet(updateSetColumns, psUpdate)) { processColumnSet(updateClauseColumns, psUpdate); counter += psUpdate.executeUpdate(); } } } } catch (SQLException e) { throw new SAXException(e); } catch (ParseException e) { throw new SAXException(e); } } else { if (inTag) { data.put(currentElement, sbData.toString()); } currentElement = null; } popPath(); inElement = false; sbData.setLength(0); } /** * Process a column set * * @param columns the columns to process * @param ps prepared statement to use * @return if data other than <code>null</code> has been set * @throws SQLException on errors * @throws ParseException on date/time conversion errors */ private boolean processColumnSet(Map<String, ColumnInfo> columns, PreparedStatement ps) throws SQLException, ParseException { boolean dataSet = false; for (String col : columns.keySet()) { ColumnInfo ci = columns.get(col); String value = data.get(col); if (insertMode && counters != null && counters.get(col) != null) { final int newVal = counters.get(col) - 1; value = String.valueOf(newVal); counters.put(col, newVal); // System.out.println("new value for " + col + ": " + newVal); } if (insertMode && presetRefColumns != null && presetRefColumns.get(col) != null) { value = data.get(presetRefColumns.get(col)); // System.out.println("Set presetRefColumn for "+col+" to ["+value+"] from column ["+presetRefColumns.get(col)+"]"); } if (value == null) ps.setNull(ci.index, ci.columnType); else { dataSet = true; switch (ci.columnType) { case Types.BIGINT: case Types.NUMERIC: if (DBG) LOG.info("BigInt " + ci.index + "->" + new BigDecimal(value)); ps.setBigDecimal(ci.index, new BigDecimal(value)); break; case java.sql.Types.DOUBLE: if (DBG) LOG.info("Double " + ci.index + "->" + Double.parseDouble(value)); ps.setDouble(ci.index, Double.parseDouble(value)); break; case java.sql.Types.FLOAT: case java.sql.Types.REAL: if (DBG) LOG.info("Float " + ci.index + "->" + Float.parseFloat(value)); ps.setFloat(ci.index, Float.parseFloat(value)); break; case java.sql.Types.TIMESTAMP: case java.sql.Types.DATE: if (DBG) LOG.info("Timestamp/Date " + ci.index + "->" + FxFormatUtils.getDateTimeFormat().parse(value)); ps.setTimestamp(ci.index, new Timestamp(FxFormatUtils.getDateTimeFormat().parse(value).getTime())); break; case Types.TINYINT: case Types.SMALLINT: if (DBG) LOG.info("Integer " + ci.index + "->" + Integer.valueOf(value)); ps.setInt(ci.index, Integer.valueOf(value)); break; case Types.INTEGER: case Types.DECIMAL: try { if (DBG) LOG.info("Long " + ci.index + "->" + Long.valueOf(value)); ps.setLong(ci.index, Long.valueOf(value)); } catch (NumberFormatException e) { //Fallback (temporary) for H2 if the reported long is a big decimal (tree...) ps.setBigDecimal(ci.index, new BigDecimal(value)); } break; case Types.BIT: case Types.CHAR: case Types.BOOLEAN: if (DBG) LOG.info("Boolean " + ci.index + "->" + value); if ("1".equals(value) || "true".equals(value)) ps.setBoolean(ci.index, true); else ps.setBoolean(ci.index, false); break; case Types.LONGVARBINARY: case Types.VARBINARY: case Types.BLOB: case Types.BINARY: ZipEntry bin = zip.getEntry(value); if (bin == null) { LOG.error("Failed to lookup binary [" + value + "]!"); ps.setNull(ci.index, ci.columnType); break; } try { ps.setBinaryStream(ci.index, zip.getInputStream(bin), (int) bin.getSize()); } catch (IOException e) { LOG.error("IOException importing binary [" + value + "]: " + e.getMessage(), e); } break; case Types.CLOB: case Types.LONGVARCHAR: case Types.VARCHAR: case SQL_LONGNVARCHAR: case SQL_NCHAR: case SQL_NCLOB: case SQL_NVARCHAR: if (DBG) LOG.info("String " + ci.index + "->" + value); ps.setString(ci.index, value); break; default: LOG.warn("Unhandled type [" + ci.columnType + "] for column [" + col + "]"); } } } return dataSet; } /** * {@inheritDoc} */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (inElement) sbData.append(ch, start, length); } }; handler.processingInstruction("fx_mode", "insert"); parser.parse(zip.getInputStream(ze), handler); if (updateColumns.length > 0 && executeUpdatePhase) { handler.processingInstruction("fx_mode", "update"); parser.parse(zip.getInputStream(ze), handler); } } finally { Database.closeObjects(GenericDivisionImporter.class, psInsert, psUpdate); } }
From source file:org.apache.synapse.mediators.db.AbstractDBMediator.java
/** * Return a Prepared statement for the given Statement object, which is ready to be executed * * @param stmnt SQL stataement to be executed * @param con The connection to be used * @param msgCtx Current message context * @return a PreparedStatement//from ww w.jav a 2s .c o m * @throws SQLException on error */ protected PreparedStatement getPreparedStatement(Statement stmnt, Connection con, MessageContext msgCtx) throws SQLException { SynapseLog synLog = getLog(msgCtx); if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("Getting a connection from DataSource " + getDSName() + " and preparing statement : " + stmnt.getRawStatement()); } if (con == null) { String msg = "Connection from DataSource " + getDSName() + " is null."; log.error(msg); throw new SynapseException(msg); } if (dataSource instanceof BasicDataSource) { BasicDataSource basicDataSource = (BasicDataSource) dataSource; int numActive = basicDataSource.getNumActive(); int numIdle = basicDataSource.getNumIdle(); String connectionId = Integer.toHexString(con.hashCode()); DBPoolView dbPoolView = getDbPoolView(); if (dbPoolView != null) { dbPoolView.setNumActive(numActive); dbPoolView.setNumIdle(numIdle); dbPoolView.updateConnectionUsage(connectionId); } if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("[ DB Connection : " + con + " ]"); synLog.traceOrDebug("[ DB Connection instance identifier : " + connectionId + " ]"); synLog.traceOrDebug("[ Number of Active Connection : " + numActive + " ]"); synLog.traceOrDebug("[ Number of Idle Connection : " + numIdle + " ]"); } } PreparedStatement ps = con.prepareStatement(stmnt.getRawStatement()); // set parameters if any List<Statement.Parameter> params = stmnt.getParameters(); int column = 1; for (Statement.Parameter param : params) { if (param == null) { continue; } String value = (param.getPropertyName() != null ? param.getPropertyName() : param.getXpath().stringValueOf(msgCtx)); if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("Setting as parameter : " + column + " value : " + value + " as JDBC Type : " + param.getType() + "(see java.sql.Types for valid " + "types)"); } switch (param.getType()) { // according to J2SE 1.5 /docs/guide/jdbc/getstart/mapping.html case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: { if (value != null && value.length() != 0) { ps.setString(column++, value); } else { ps.setString(column++, null); } break; } case Types.NUMERIC: case Types.DECIMAL: { if (value != null && value.length() != 0) { ps.setBigDecimal(column++, new BigDecimal(value)); } else { ps.setBigDecimal(column++, null); } break; } case Types.BIT: { if (value != null && value.length() != 0) { ps.setBoolean(column++, Boolean.parseBoolean(value)); } else { ps.setNull(column++, Types.BIT); } break; } case Types.TINYINT: { if (value != null && value.length() != 0) { ps.setByte(column++, Byte.parseByte(value)); } else { ps.setNull(column++, Types.TINYINT); } break; } case Types.SMALLINT: { if (value != null && value.length() != 0) { ps.setShort(column++, Short.parseShort(value)); } else { ps.setNull(column++, Types.SMALLINT); } break; } case Types.INTEGER: { if (value != null && value.length() != 0) { ps.setInt(column++, Integer.parseInt(value)); } else { ps.setNull(column++, Types.INTEGER); } break; } case Types.BIGINT: { if (value != null && value.length() != 0) { ps.setLong(column++, Long.parseLong(value)); } else { ps.setNull(column++, Types.BIGINT); } break; } case Types.REAL: { if (value != null && value.length() != 0) { ps.setFloat(column++, Float.parseFloat(value)); } else { ps.setNull(column++, Types.REAL); } break; } case Types.FLOAT: { if (value != null && value.length() != 0) { ps.setDouble(column++, Double.parseDouble(value)); } else { ps.setNull(column++, Types.FLOAT); } break; } case Types.DOUBLE: { if (value != null && value.length() != 0) { ps.setDouble(column++, Double.parseDouble(value)); } else { ps.setNull(column++, Types.DOUBLE); } break; } // skip BINARY, VARBINARY and LONGVARBINARY case Types.DATE: { if (value != null && value.length() != 0) { ps.setDate(column++, Date.valueOf(value)); } else { ps.setNull(column++, Types.DATE); } break; } case Types.TIME: { if (value != null && value.length() != 0) { ps.setTime(column++, Time.valueOf(value)); } else { ps.setNull(column++, Types.TIME); } break; } case Types.TIMESTAMP: { if (value != null && value.length() != 0) { ps.setTimestamp(column++, Timestamp.valueOf(value)); } else { ps.setNull(column++, Types.TIMESTAMP); } break; } // skip CLOB, BLOB, ARRAY, DISTINCT, STRUCT, REF, JAVA_OBJECT default: { String msg = "Trying to set an un-supported JDBC Type : " + param.getType() + " against column : " + column + " and statement : " + stmnt.getRawStatement() + " used by a DB mediator against DataSource : " + getDSName() + " (see java.sql.Types for valid type values)"; handleException(msg, msgCtx); } } } if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("Successfully prepared statement : " + stmnt.getRawStatement() + " against DataSource : " + getDSName()); } return ps; }
From source file:edu.ku.brc.specify.toycode.mexconabio.MexConvToSQLNew.java
public void convert(final String tableName, final String fileName) { String str = ""; int fldLen = 0; int inx = 0;/*from w w w. j a v a 2 s. c om*/ Connection conn = null; Statement stmt = null; try { conn = DriverManager.getConnection( "jdbc:mysql://localhost/mex?characterEncoding=UTF-8&autoReconnect=true", "root", "root"); stmt = conn.createStatement(); int[] fieldLengths = null; BasicSQLUtils.deleteAllRecordsFromTable(conn, tableName, SERVERTYPE.MySQL); Vector<Integer> types = new Vector<Integer>(); Vector<String> names = new Vector<String>(); String selectStr = null; String prepareStr = null; try { prepareStr = FileUtils.readFileToString(new File("prepare_stmt.txt")); selectStr = FileUtils.readFileToString(new File("select.txt")); } catch (IOException e) { e.printStackTrace(); } int idInx = selectStr.indexOf("ID,"); if (idInx == 0) { selectStr = selectStr.substring(3); } File file = new File("/Users/rods/Documents/" + fileName); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); //SimpleDateFormat stf = new SimpleDateFormat("k:mm:ss"); int rowCnt = 0; try { System.out.println(prepareStr); PreparedStatement pStmt = conn.prepareStatement(prepareStr); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8")); str = in.readLine(); String[] fieldNames = StringUtils.split(str, ","); //String[] fieldNamesDB = StringUtils.split(selectStr, ","); String sql = "SELECT " + selectStr + " FROM " + tableName; System.out.println(sql); ResultSet rs = stmt.executeQuery(sql); ResultSetMetaData rsmd = rs.getMetaData(); fieldLengths = new int[rsmd.getColumnCount()]; for (int i = 1; i <= rsmd.getColumnCount(); i++) { fieldLengths[i - 1] = rsmd.getPrecision(i); types.add(rsmd.getColumnType(i)); names.add(rsmd.getColumnName(i)); System.out.println((i > 1 ? fieldNames[i - 2] : "ID") + " / " + rsmd.getColumnName(i) + " - " + rsmd.getPrecision(i)); } int numCols = rsmd.getColumnCount(); rs.close(); System.out.println("Number of Fields: " + numCols); str = in.readLine(); while (str != null) { //System.err.println(str); str = StringUtils.replace(str.substring(1, str.length() - 1), "\",\"", "|"); Vector<String> fields = split(str); if (fields.size() != numCols) { System.out.println("numCols: " + numCols + " != " + fields.size() + "fields.size()"); continue; } int col = 1; inx = 0; for (String fld : fields) { String field = fld.trim(); //if (field.length() > 1) //{ // field = field.substring(1, field.length()-1); //} //if (inx > 204) break; fldLen = field.length(); pStmt.setObject(col, null); switch (types.get(inx)) { case java.sql.Types.LONGVARCHAR: case java.sql.Types.VARCHAR: case java.sql.Types.LONGNVARCHAR: { if (field.length() > 0) { if (field.length() <= fieldLengths[inx]) { pStmt.setString(col, field); } else { System.err.println(String.format("The data for `%s` (%d) is too big %d f[%s]", names.get(inx), fieldLengths[inx], field.length(), field)); pStmt.setString(col, null); } } else { pStmt.setString(col, null); } } break; case java.sql.Types.DOUBLE: case java.sql.Types.FLOAT: { if (StringUtils.isNotEmpty(field)) { if (StringUtils.isNumeric(field)) { pStmt.setDouble(col, field.length() > 0 ? Double.parseDouble(field) : null); } else { System.err.println(col + " Bad Number[" + field + "] "); pStmt.setDate(col, null); } } else { pStmt.setDate(col, null); } } break; case java.sql.Types.INTEGER: { if (StringUtils.isNotEmpty(field)) { if (StringUtils.isNumeric(field)) { pStmt.setInt(col, field.length() > 0 ? Integer.parseInt(field) : null); } else { System.err.println(col + " Bad Number[" + field + "] "); pStmt.setDate(col, null); } } else { pStmt.setDate(col, null); } } break; case java.sql.Types.TIME: { Time time = null; try { time = Time.valueOf(field); } catch (Exception ex) { } pStmt.setTime(col, time); } break; case java.sql.Types.DATE: { try { if (StringUtils.isNotEmpty(field)) { if (StringUtils.contains(field, "/")) { field = StringUtils.replace(field, "/", "-"); } else if (StringUtils.contains(field, " ")) { field = StringUtils.replace(field, " ", "-"); } pStmt.setDate(col, field.length() > 0 ? new java.sql.Date(sdf.parse(field).getTime()) : null); } else { pStmt.setDate(col, null); } } catch (Exception ex) { System.err.println(col + " Bad Date[" + field + "]\n" + str); pStmt.setDate(col, null); } } break; default: { System.err.println("Error - " + types.get(inx)); } } inx++; col++; } pStmt.execute(); str = in.readLine(); rowCnt++; } in.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (Exception e) { System.err.println("Row: " + rowCnt); System.err.println(str); System.err.println(inx + " " + fieldLengths[inx] + " - Field Len: " + fldLen); e.printStackTrace(); } /*BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); while (bis.available() > 0) { int bytesRead = bis.read(bytes); if (bytesRead > 0) { System.arraycopy(bytes, bytesRead, buffer, bufEndInx, bytesRead); bufEndInx += bytesRead; int inx = 0; while (inx < bufEndInx) { if (buffer[inx] != '\n') { String line = } inx++; } } }*/ } catch (Exception ex) { ex.printStackTrace(); } finally { try { stmt.close(); conn.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
From source file:org.moqui.impl.entity.EntityJavaUtil.java
public static void setPreparedStatementValue(PreparedStatement ps, int index, Object value, FieldInfo fi, boolean useBinaryTypeForBlob, EntityFacade efi) throws EntityException { try {//from w ww .j av a 2 s .c o m // allow setting, and searching for, String values for all types; JDBC driver should handle this okay if (value instanceof CharSequence) { ps.setString(index, value.toString()); } else { switch (fi.typeValue) { case 1: if (value != null) { ps.setString(index, value.toString()); } else { ps.setNull(index, Types.VARCHAR); } break; case 2: if (value != null) { Class valClass = value.getClass(); if (valClass == Timestamp.class) { ps.setTimestamp(index, (Timestamp) value, efi.getCalendarForTzLc()); } else if (valClass == java.sql.Date.class) { ps.setDate(index, (java.sql.Date) value, efi.getCalendarForTzLc()); } else if (valClass == java.util.Date.class) { ps.setTimestamp(index, new Timestamp(((java.util.Date) value).getTime()), efi.getCalendarForTzLc()); } else { throw new IllegalArgumentException("Class " + valClass.getName() + " not allowed for date-time (Timestamp) fields, for field " + fi.entityName + "." + fi.name); } } else { ps.setNull(index, Types.TIMESTAMP); } break; case 3: Time tm = (Time) value; // logger.warn("=================== setting time tm=${tm} tm long=${tm.getTime()}, cal=${cal}") if (value != null) { ps.setTime(index, tm, efi.getCalendarForTzLc()); } else { ps.setNull(index, Types.TIME); } break; case 4: if (value != null) { Class valClass = value.getClass(); if (valClass == java.sql.Date.class) { java.sql.Date dt = (java.sql.Date) value; // logger.warn("=================== setting date dt=${dt} dt long=${dt.getTime()}, cal=${cal}") ps.setDate(index, dt, efi.getCalendarForTzLc()); } else if (valClass == Timestamp.class) { ps.setDate(index, new java.sql.Date(((Timestamp) value).getTime()), efi.getCalendarForTzLc()); } else if (valClass == java.util.Date.class) { ps.setDate(index, new java.sql.Date(((java.util.Date) value).getTime()), efi.getCalendarForTzLc()); } else { throw new IllegalArgumentException("Class " + valClass.getName() + " not allowed for date fields, for field " + fi.entityName + "." + fi.name); } } else { ps.setNull(index, Types.DATE); } break; case 5: if (value != null) { ps.setInt(index, ((Number) value).intValue()); } else { ps.setNull(index, Types.NUMERIC); } break; case 6: if (value != null) { ps.setLong(index, ((Number) value).longValue()); } else { ps.setNull(index, Types.NUMERIC); } break; case 7: if (value != null) { ps.setFloat(index, ((Number) value).floatValue()); } else { ps.setNull(index, Types.NUMERIC); } break; case 8: if (value != null) { ps.setDouble(index, ((Number) value).doubleValue()); } else { ps.setNull(index, Types.NUMERIC); } break; case 9: if (value != null) { Class valClass = value.getClass(); // most common cases BigDecimal, Double, Float; then allow any Number if (valClass == BigDecimal.class) { ps.setBigDecimal(index, (BigDecimal) value); } else if (valClass == Double.class) { ps.setDouble(index, (Double) value); } else if (valClass == Float.class) { ps.setFloat(index, (Float) value); } else if (value instanceof Number) { ps.setDouble(index, ((Number) value).doubleValue()); } else { throw new IllegalArgumentException("Class " + valClass.getName() + " not allowed for number-decimal (BigDecimal) fields, for field " + fi.entityName + "." + fi.name); } } else { ps.setNull(index, Types.NUMERIC); } break; case 10: if (value != null) { ps.setBoolean(index, (Boolean) value); } else { ps.setNull(index, Types.BOOLEAN); } break; case 11: if (value != null) { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeObject(value); oos.close(); byte[] buf = os.toByteArray(); os.close(); ByteArrayInputStream is = new ByteArrayInputStream(buf); ps.setBinaryStream(index, is, buf.length); is.close(); } catch (IOException ex) { throw new EntityException( "Error setting serialized object, for field " + fi.entityName + "." + fi.name, ex); } } else { if (useBinaryTypeForBlob) { ps.setNull(index, Types.BINARY); } else { ps.setNull(index, Types.BLOB); } } break; case 12: if (value instanceof byte[]) { ps.setBytes(index, (byte[]) value); /* } else if (value instanceof ArrayList) { ArrayList valueAl = (ArrayList) value; byte[] theBytes = new byte[valueAl.size()]; valueAl.toArray(theBytes); ps.setBytes(index, theBytes); */ } else if (value instanceof ByteBuffer) { ByteBuffer valueBb = (ByteBuffer) value; ps.setBytes(index, valueBb.array()); } else if (value instanceof Blob) { Blob valueBlob = (Blob) value; // calling setBytes instead of setBlob // ps.setBlob(index, (Blob) value) // Blob blb = value ps.setBytes(index, valueBlob.getBytes(1, (int) valueBlob.length())); } else { if (value != null) { throw new IllegalArgumentException("Type not supported for BLOB field: " + value.getClass().getName() + ", for field " + fi.entityName + "." + fi.name); } else { if (useBinaryTypeForBlob) { ps.setNull(index, Types.BINARY); } else { ps.setNull(index, Types.BLOB); } } } break; case 13: if (value != null) { ps.setClob(index, (Clob) value); } else { ps.setNull(index, Types.CLOB); } break; case 14: if (value != null) { ps.setTimestamp(index, (Timestamp) value); } else { ps.setNull(index, Types.TIMESTAMP); } break; // TODO: is this the best way to do collections and such? case 15: if (value != null) { ps.setObject(index, value, Types.JAVA_OBJECT); } else { ps.setNull(index, Types.JAVA_OBJECT); } break; } } } catch (SQLException sqle) { throw new EntityException("SQL Exception while setting value [" + value + "](" + (value != null ? value.getClass().getName() : "null") + "), type " + fi.type + ", for field " + fi.entityName + "." + fi.name + ": " + sqle.toString(), sqle); } catch (Exception e) { throw new EntityException( "Error while setting value for field " + fi.entityName + "." + fi.name + ": " + e.toString(), e); } }
From source file:org.getobjects.eoaccess.EOAdaptorChannel.java
protected PreparedStatement _prepareStatementWithBinds(final String _sql, final List<Map<String, Object>> _binds) { boolean isDebugOn = log.isDebugEnabled(); if (_sql == null || _sql.length() == 0) return null; final PreparedStatement stmt = this._createPreparedStatement(_sql); if (stmt == null) return null; if (_binds == null) { if (isDebugOn) log.debug("statement to prepare has no binds .."); return stmt; /* hm, statement has no binds */ }// w w w . ja va 2 s . co m /* fill in parameters */ if (isDebugOn) log.debug("prepare binds: " + _binds); try { /* Fill statement with bindg values */ for (int i = 0; i < _binds.size(); i++) { /* a dictionary with such keys: * BindVariableAttributeKey - the EOAttribute of the value * BindVariableValueKey - the actual value */ final Map<String, Object> bind = _binds.get(i); final EOAttribute attribute = (EOAttribute) bind.get(EOSQLExpression.BindVariableAttributeKey); final Object value = bind.get(EOSQLExpression.BindVariableValueKey); int sqlType = this.sqlTypeForValue(value, attribute); if (isDebugOn) { log.debug(" bind attribute: " + attribute); log.debug(" value: " + value + " / " + (value != null ? value.getClass() : "[NULL]")); log.debug(" type: " + sqlType); } if (value == null) stmt.setNull(i + 1, sqlType); else { switch (sqlType) { case java.sql.Types.NULL: stmt.setNull(i + 1, java.sql.Types.VARCHAR); // CRAP break; // TODO: customize value processing for types case java.sql.Types.VARCHAR: case java.sql.Types.TIMESTAMP: case java.sql.Types.DATE: case java.sql.Types.INTEGER: case java.sql.Types.BIGINT: case java.sql.Types.BOOLEAN: default: if (value instanceof String) stmt.setString(i + 1, (String) value); else if (value instanceof Boolean) stmt.setBoolean(i + 1, (Boolean) value); else if (value instanceof Integer) stmt.setInt(i + 1, (Integer) value); else if (value instanceof Double) stmt.setDouble(i + 1, (Double) value); else if (value instanceof BigDecimal) stmt.setBigDecimal(i + 1, (BigDecimal) value); else if (value instanceof Long) stmt.setLong(i + 1, (Long) value); else if (value instanceof java.util.Date) { // TBD: shouldn't we use setDate with a proper Calendar? stmt.setTimestamp(i + 1, new java.sql.Timestamp(((Date) value).getTime())); } else if (value instanceof java.util.Calendar) { // TBD: shouldn't we use setDate with a proper Calendar? final Date vd = ((Calendar) value).getTime(); stmt.setTimestamp(i + 1, new java.sql.Timestamp(vd.getTime())); } else if (value instanceof java.sql.Date) { /* Note: this is just the DATE component, no TIME */ stmt.setDate(i + 1, (java.sql.Date) value); } else if (value instanceof byte[]) stmt.setBytes(i + 1, (byte[]) value); else if (value instanceof EOQualifierVariable) { log.error("detected unresolved qualifier variable: " + value); this._releaseResources(stmt, null); return null; } else { log.warn("using String column for value: " + value + " (" + value.getClass() + ")"); } } } } } catch (NullPointerException e) { this.lastException = e; log.error("could not apply binds to prepared statement (null ptr): " + _sql, e); this._releaseResources(stmt, null); return null; } catch (SQLException e) { this.lastException = e; log.error("could not apply binds to prepared statement: " + _sql, e); this._releaseResources(stmt, null); return null; } return stmt; }
From source file:net.sf.farrago.namespace.sfdc.SfdcUdx.java
public static void query(String query, String types, PreparedStatement resultInserter) throws SQLException { SoapBindingStub binding = (SoapBindingStub) FarragoUdrRuntime.getDataServerRuntimeSupport(null); try {//from w w w.j a v a2s . c om QueryOptions qo = new QueryOptions(); int batchsize = 500; qo.setBatchSize(new Integer(batchsize)); binding.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(), "QueryOptions", qo); String objName = query; int fromIdx = query.lastIndexOf(" from"); if (fromIdx > 0) { objName = query.substring(fromIdx + 6); } // strip off quotes for boolean values query = stripQuotes(query, objName); log.info("SFDC Query: " + query); QueryResult qr = binding.query(query); if (qr.isDone()) { if (qr.getRecords() != null) { log.info(SfdcResource.instance().RetrievedAllRecordsMsg .str(Integer.toString(qr.getRecords().length), objName)); } } else { if (qr.getRecords() != null) { log.info(SfdcResource.instance().RetrievingRecordsMsg .str(Integer.toString(qr.getRecords().length), objName)); } } SObject[] records = qr.getRecords(); String[] metadataType = types.split(","); // query is of following format: // "select col1,col2,... from" String cols = query.substring(7); fromIdx = cols.lastIndexOf(" from"); cols = cols.substring(0, fromIdx); cols = cols.trim(); String[] columnValues = new String[metadataType.length]; if (records != null) { boolean bContinue = true; while (bContinue) { // for each record returned in query, // get value of each field for (int i = 0; i < records.length; i++) { MessageElement[] elements = records[i].get_any(); if (elements != null) { for (int j = 0; j < elements.length; j++) { MessageElement elt = elements[j]; String eltVal = elt.getValue(); columnValues[j] = (eltVal != null) ? eltVal : "null"; if (metadataType[j].indexOf("TIMESTAMP") != -1) { // TIMESTAMP if (eltVal != null) { String tstampstr = eltVal.replace("T", " "); tstampstr = tstampstr.substring(0, tstampstr.indexOf(".")); java.sql.Timestamp tstamp = java.sql.Timestamp.valueOf(tstampstr); resultInserter.setTimestamp(j + 1, tstamp); } else { resultInserter.setNull(j + 1, java.sql.Types.TIMESTAMP); } } else if (metadataType[j].indexOf("TIME") != -1) { // TIME if (eltVal != null) { String timestr = eltVal.substring(0, eltVal.indexOf(".")); java.sql.Time time = java.sql.Time.valueOf(timestr); resultInserter.setTime(j + 1, time); } else { resultInserter.setNull(j + 1, java.sql.Types.TIME); } } else if (metadataType[j].indexOf("DATE") != -1) { // DATE if (eltVal != null) { java.sql.Date dt = java.sql.Date.valueOf(eltVal); resultInserter.setDate(j + 1, dt); } else { resultInserter.setNull(j + 1, java.sql.Types.DATE); } } else if (metadataType[j].indexOf("INTEGER") != -1) { // INTEGER if (eltVal != null) { int iValue = 0; iValue = Integer.parseInt(eltVal); resultInserter.setInt(j + 1, iValue); } else { resultInserter.setNull(j + 1, java.sql.Types.INTEGER); } } else if (metadataType[j].indexOf("DOUBLE") != -1) { // DOUBLE if (eltVal != null) { resultInserter.setDouble(j + 1, Double.parseDouble(eltVal)); } else { resultInserter.setNull(j + 1, java.sql.Types.DOUBLE); } } else if (eltVal != null) { // VARCHAR - default int rightParen = metadataType[j].indexOf(")"); int prec = Integer.parseInt(metadataType[j].substring(8, rightParen)); if (eltVal.length() > prec) { eltVal = eltVal.substring(0, prec); columnValues[j] = eltVal; } resultInserter.setString(j + 1, eltVal); } else { resultInserter.setNull(j + 1, java.sql.Types.VARCHAR); } } resultInserter.executeUpdate(); } } if (qr.isDone()) { bContinue = false; } else { boolean relogin = true; int retryCnt = 0; while (relogin) { try { qr = binding.queryMore(qr.getQueryLocator()); relogin = false; } catch (AxisFault a) { if (a.getFaultString().contains("Invalid Session ID") && (retryCnt < RETRY_CNT)) { relogin = true; retryCnt++; binding = (SoapBindingStub) FarragoUdrRuntime .getDataServerRuntimeSupport(binding); } else { throw a; } } } records = qr.getRecords(); if (qr.isDone()) { if (qr.getRecords() != null) { log.info(SfdcResource.instance().RetrievedAllRecordsMsg .str(Integer.toString(qr.getRecords().length), objName)); } } else { if (qr.getRecords() != null) { log.info(SfdcResource.instance().RetrievingRecordsMsg .str(Integer.toString(qr.getRecords().length), objName)); } } } } } } catch (AxisFault ae) { SQLException retryExcn = new SQLException(ae.getFaultString(), null, 460150); Exception chainedEx = FarragoResource.instance().RetryableFailure.ex(retryExcn); throw SfdcResource.instance().BindingCallException.ex(ae.getFaultString(), chainedEx); } catch (RemoteException re) { SQLException retryExcn = new SQLException(re.getMessage(), null, 460150); Exception chainedEx = FarragoResource.instance().RetryableFailure.ex(retryExcn); throw SfdcResource.instance().BindingCallException.ex(re.getMessage(), chainedEx); } }
From source file:edu.ku.brc.specify.toycode.mexconabio.BuildFromRecovery.java
/** * /*from w w w .j a v a 2 s.co m*/ */ public void process() throws SQLException { buildTags = new BuildTags(); buildTags.setDbConn(dbConn); buildTags.setDbConn2(dbConn); buildTags.initialPrepareStatements(); BasicSQLUtils.setDBConnection(dbConn); IdMapperMgr idMapperMgr = IdMapperMgr.getInstance(); idMapperMgr.setDBs(srcDBConn2, dbConn); geoStmt1 = dbConn.prepareStatement( "SELECT GeographyID FROM geography WHERE RankID = ? AND ParentID = ? AND LOWER(Abbrev) = ?"); geoStmt2 = dbConn .prepareStatement("SELECT GeographyID FROM geography WHERE RankID = ? AND LOWER(Abbrev) = ?"); agentStmt = dbConn .prepareStatement("SELECT AgentID FROM agent WHERE LOWER(FirstName) = ? AND LOWER(LastName) = ?"); tagStmt = dbConn.prepareStatement( "SELECT CollectionObjectID FROM collectionobject WHERE CollectionID = 4 AND LOWER(FieldNumber) = ?"); BasicSQLUtils.update(srcDBConn, "UPDATE recovery SET r_date = null WHERE r_date = '0000-00-00'"); boolean doTags = true; if (doTags) { int divId = 2; int dspId = 3; int colId = 32768; String sql = "SELECT tagid, " + "r_city, r_state, r_zip, r_country, r_date, r_lat, r_long, " + "reporter_first, reporter_last, reporter_city, reporter_state, reporter_country, reporter_zip, " + "dir, dist, gender, " + "t_first, t_middle, t_last, t_city, t_state, t_country, t_postalcode, t_org, t_lat, t_long, t_date FROM recovery ORDER BY recovid ASC"; Statement stmt = srcDBConn.createStatement(); stmt.setFetchSize(Integer.MIN_VALUE); log.debug("Querying for Tags..."); ResultSet rs = stmt.executeQuery(sql); int cnt = 0; log.debug("Done querying for Tags..."); Calendar cal = Calendar.getInstance(); Timestamp ts = new Timestamp(cal.getTime().getTime()); String common = "TimestampCreated, Version, CreatedByAgentID"; String coStr = String.format( "INSERT INTO collectionobject (CatalogNumber, FieldNumber, Text1, Text2, Remarks, CollectionID, CollectionMemberId, CollectingEventID, %s) VALUES(?,?,?,?,?,?,?,?,?,?,?)", common); String ceStr = String.format( "INSERT INTO collectingevent (StartDate, DisciplineID, LocalityID, %s) VALUES(?,?,?,?,?,?)", common); String lcStr = String.format( "INSERT INTO locality (Latitude1, Longitude1, SrcLatLongUnit, Lat1text, Long1text, LatLongType, DisciplineID, LocalityName, GeographyID, %s) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", common); String clStr = String.format( "INSERT INTO collector (OrderNumber, IsPrimary, CollectingEventID, DivisionID, AgentID, %s) VALUES(?,?,?,?,?,?,?,?)", common); String rlStr = String.format( "INSERT INTO collectionrelationship (collectionRelTypeID, LeftSideCollectionID, RightSideCollectionID, %s) VALUES(?,?,?,?,?,?)", common); String agStr = String .format("INSERT INTO agent (AgentType, FirstName, LastName, %s) VALUES(?,?,?,?,?,?)", common); String adStr = String.format( "INSERT INTO address (City, State, PostalCode, Country, AgentID, %s) VALUES(?,?,?,?, ?,?,?,?)", common); String lcUpdateStr = "UPDATE locality SET Latitude1=?, Longitude1=?, SrcLatLongUnit=?, Lat1text=?, Long1text=?, LatLongType=? WHERE LocalityID = ?"; String lcStr2 = "SELECT LocalityID FROM locality WHERE LocalityName LIKE ? AND LocalityName LIKE ?"; PreparedStatement coStmt = dbConn.prepareStatement(coStr); PreparedStatement ceStmt = dbConn.prepareStatement(ceStr); PreparedStatement lcStmt = dbConn.prepareStatement(lcStr); PreparedStatement clStmt = dbConn.prepareStatement(clStr); PreparedStatement rlStmt = dbConn.prepareStatement(rlStr); PreparedStatement agStmt = dbConn.prepareStatement(agStr); PreparedStatement adStmt = dbConn.prepareStatement(adStr); PreparedStatement lcUpStmt = dbConn.prepareStatement(lcUpdateStr); PreparedStatement lcStmt2 = dbConn.prepareStatement(lcStr2); int recNum = 1; while (rs.next()) { String tag = rs.getString(1); String city = rs.getString(2); String state = rs.getString(3); String zip = rs.getString(4); String country = rs.getString(5); Date date = rs.getDate(6); double lat = rs.getDouble(7); boolean isLatNull = rs.wasNull(); double lon = rs.getDouble(8); boolean isLonNull = rs.wasNull(); String dir = rs.getString(9); String dist = rs.getString(10); String gender = rs.getString(11); String rep_first = rs.getString(12); String rep_last = rs.getString(13); String rep_city = rs.getString(14); String rep_state = rs.getString(15); String rep_country = rs.getString(16); String rep_zip = rs.getString(17); String t_first = rs.getString(18); //String t_middle = rs.getString(19); String t_last = rs.getString(20); String t_city = rs.getString(21); String t_state = rs.getString(22); String t_country = rs.getString(23); String t_zip = rs.getString(24); //String t_org = rs.getString(25); double t_lat = rs.getDouble(26); boolean isTLatNull = rs.wasNull(); double t_lon = rs.getDouble(27); boolean isTLonNull = rs.wasNull(); //String oldState = state; city = condense(rep_city, t_city, city); state = condense(rep_state, state, t_state); country = condense(rep_country, country, t_country); zip = condense(rep_zip, zip, t_zip); rep_first = condense(rep_first, t_first); rep_last = condense(rep_last, t_last); /*boolean debug = ((rep_state != null && rep_state.equals("IA")) || (t_state != null && t_state.equals("IA")) || (oldState != null && oldState.equals("IA"))); if (debug && (state == null || !state.equals("IA"))) { System.out.println("ouch"); }*/ if (rep_first != null && rep_first.length() > 50) { rep_first = rep_first.substring(0, 50); } lat = isLatNull && !isTLatNull ? t_lat : lat; lon = isLonNull && !isTLonNull ? t_lon : lon; try { // (Latitude1, Longitude1, SrcLatLongUnit, Lat1text, Long1text, LatLongType, DisciplineID, MaxElevation, LocalityName, GeographyID Integer geoId = buildTags.getGeography(country, state, null); // Latitude varies between -90 and 90, and Longitude between -180 and 180. if (lat < -90.0 || lat > 90.0) { lcStmt.setObject(1, null); lcStmt.setObject(4, null); } else { lcStmt.setDouble(1, lat); lcStmt.setString(4, Double.toString(lat)); lcUpStmt.setDouble(1, lat); lcUpStmt.setString(4, Double.toString(lat)); } if (lon < -180.0 || lon > 180.0) { lcStmt.setObject(2, null); lcStmt.setObject(5, null); } else { lcStmt.setDouble(2, lon); lcStmt.setString(5, Double.toString(lon)); lcUpStmt.setDouble(2, lon); lcUpStmt.setString(5, Double.toString(lon)); } String locName = null; String fullName = null; Integer locId = null; geoId = buildTags.getGeography(country, state, null); if (geoId != null) { fullName = geoFullNameHash.get(geoId); if (fullName == null) { fullName = BasicSQLUtils .querySingleObj("SELECT FullName FROM geography WHERE GeographyID = " + geoId); geoFullNameHash.put(geoId, fullName); } if (StringUtils.isNotEmpty(city)) { locName = city + ", " + fullName; } else { locName = fullName; } locId = localityHash.get(locName); if (locId == null) { lcStmt2.setString(1, "%" + city); lcStmt2.setString(2, country + "%"); ResultSet lcRS = lcStmt2.executeQuery(); if (lcRS.next()) { locId = lcRS.getInt(1); if (!lcRS.wasNull()) { localityHash.put(locName, locId); } } lcRS.close(); } } else { //unknown++; fullName = "Unknown"; locName = buildTags.buildLocalityName(city, fullName); geoId = 27507; // Unknown locId = localityHash.get(locName); //log.error("Couldn't find matching geography["+country+", "+state+", "+county+"]"); } if (locId == null) { lcStmt.setByte(3, (byte) 0); lcStmt.setString(6, "Point"); lcStmt.setInt(7, dspId); lcStmt.setString(8, getLocalityName(country, state, null, city)); lcStmt.setObject(9, geoId); lcStmt.setTimestamp(10, ts); lcStmt.setInt(11, 1); lcStmt.setInt(12, 1); lcStmt.executeUpdate(); locId = BasicSQLUtils.getInsertedId(lcStmt); } else if (!isLatNull && !isLonNull) { int count = BasicSQLUtils.getCountAsInt( "SELECT COUNT(*) FROM locality WHERE Latitude1 IS NULL AND Longitude1 IS NULL AND LocalityID = " + locId); if (count == 1) { lcUpStmt.setByte(3, (byte) 0); lcUpStmt.setString(6, "Point"); lcUpStmt.setInt(7, locId); lcUpStmt.executeUpdate(); } } // (StartDate, Method, DisciplineID, LocalityID ceStmt.setDate(1, date); ceStmt.setInt(2, dspId); ceStmt.setInt(3, locId); ceStmt.setTimestamp(4, ts); ceStmt.setInt(5, 1); ceStmt.setInt(6, 1); ceStmt.executeUpdate(); Integer ceId = BasicSQLUtils.getInsertedId(ceStmt); //(CatalogNumber, FieldNumber, Text1, Remarks, CollectionID, CollectionMemberId coStmt.setString(1, String.format("%09d", recNum++)); coStmt.setString(2, tag); coStmt.setString(3, gender); coStmt.setString(4, dir); coStmt.setString(5, dist); coStmt.setInt(6, colId); coStmt.setInt(7, colId); coStmt.setInt(8, ceId); coStmt.setTimestamp(9, ts); coStmt.setInt(10, 1); coStmt.setInt(11, 1); coStmt.executeUpdate(); //Integer coId = BasicSQLUtils.getInsertedId(coStmt); Integer agentId = getAgentId(agentStmt, rep_first, rep_last); if (agentId == null) { agStmt.setInt(1, 0); agStmt.setString(2, rep_first); agStmt.setString(3, rep_last); agStmt.setTimestamp(4, ts); agStmt.setInt(5, 1); agStmt.setInt(6, 1); agStmt.executeUpdate(); agentId = BasicSQLUtils.getInsertedId(agStmt); if (agentId != null) { adStmt.setString(1, rep_city); adStmt.setString(2, rep_state); adStmt.setString(3, rep_zip); adStmt.setString(4, rep_country); adStmt.setInt(5, agentId); adStmt.setTimestamp(6, ts); adStmt.setInt(7, 1); adStmt.setInt(8, 1); adStmt.executeUpdate(); } else { log.error("agentId is null after being created: " + rep_first + ", " + rep_last); } } // OrderIndex, IsPrimary, CollectingEventID, DivisionID, AgentID clStmt.setInt(1, 0); clStmt.setBoolean(2, true); clStmt.setInt(3, ceId); clStmt.setInt(4, divId); clStmt.setInt(5, agentId); clStmt.setTimestamp(6, ts); clStmt.setInt(7, 1); clStmt.setInt(8, 1); clStmt.executeUpdate(); } catch (Exception ex) { log.debug(recNum + " tag[" + tag + "]"); ex.printStackTrace(); } cnt++; if (cnt % 100 == 0) { System.out.println("Col Obj: " + cnt); } } coStmt.close(); ceStmt.close(); lcStmt.close(); clStmt.close(); rlStmt.close(); agStmt.close(); adStmt.close(); lcUpStmt.close(); buildTags.cleanup(); } }
From source file:org.apache.marmotta.kiwi.persistence.KiWiConnection.java
/** * Store a new node in the database. The method will retrieve a new database id for the node and update the * passed object. Afterwards, the node data will be inserted into the database using appropriate INSERT * statements. The caller must make sure the connection is committed and closed properly. * <p/>// w w w. java 2 s . c o m * If the node already has an ID, the method will do nothing (assuming that it is already persistent) * * * @param node * @throws SQLException */ public synchronized void storeNode(KiWiNode node) throws SQLException { // ensure the data type of a literal is persisted first if (node instanceof KiWiLiteral) { KiWiLiteral literal = (KiWiLiteral) node; if (literal.getType() != null && literal.getType().getId() < 0) { storeNode(literal.getType()); } } requireJDBCConnection(); // retrieve a new node id and set it in the node object if (node.getId() < 0) { node.setId(getNextSequence()); } // distinguish the different node types and run the appropriate updates if (node instanceof KiWiUriResource) { KiWiUriResource uriResource = (KiWiUriResource) node; PreparedStatement insertNode = getPreparedStatement("store.uri"); insertNode.setLong(1, node.getId()); insertNode.setString(2, uriResource.stringValue()); insertNode.setTimestamp(3, new Timestamp(uriResource.getCreated().getTime()), calendarUTC); insertNode.executeUpdate(); } else if (node instanceof KiWiAnonResource) { KiWiAnonResource anonResource = (KiWiAnonResource) node; PreparedStatement insertNode = getPreparedStatement("store.bnode"); insertNode.setLong(1, node.getId()); insertNode.setString(2, anonResource.stringValue()); insertNode.setTimestamp(3, new Timestamp(anonResource.getCreated().getTime()), calendarUTC); insertNode.executeUpdate(); } else if (node instanceof KiWiDateLiteral) { KiWiDateLiteral dateLiteral = (KiWiDateLiteral) node; PreparedStatement insertNode = getPreparedStatement("store.tliteral"); insertNode.setLong(1, node.getId()); insertNode.setString(2, dateLiteral.stringValue()); insertNode.setTimestamp(3, new Timestamp(dateLiteral.getDateContent().getMillis()), calendarUTC); insertNode.setInt(4, dateLiteral.getDateContent().getZone().getOffset(dateLiteral.getDateContent()) / 1000); if (dateLiteral.getType() != null) insertNode.setLong(5, dateLiteral.getType().getId()); else throw new IllegalStateException("a date literal must have a datatype"); insertNode.setTimestamp(6, new Timestamp(dateLiteral.getCreated().getTime()), calendarUTC); insertNode.executeUpdate(); } else if (node instanceof KiWiIntLiteral) { KiWiIntLiteral intLiteral = (KiWiIntLiteral) node; PreparedStatement insertNode = getPreparedStatement("store.iliteral"); insertNode.setLong(1, node.getId()); insertNode.setString(2, intLiteral.getContent()); insertNode.setDouble(3, intLiteral.getDoubleContent()); insertNode.setLong(4, intLiteral.getIntContent()); if (intLiteral.getType() != null) insertNode.setLong(5, intLiteral.getType().getId()); else throw new IllegalStateException("an integer literal must have a datatype"); insertNode.setTimestamp(6, new Timestamp(intLiteral.getCreated().getTime()), calendarUTC); insertNode.executeUpdate(); } else if (node instanceof KiWiDoubleLiteral) { KiWiDoubleLiteral doubleLiteral = (KiWiDoubleLiteral) node; PreparedStatement insertNode = getPreparedStatement("store.dliteral"); insertNode.setLong(1, node.getId()); insertNode.setString(2, doubleLiteral.getContent()); insertNode.setDouble(3, doubleLiteral.getDoubleContent()); if (doubleLiteral.getType() != null) insertNode.setLong(4, doubleLiteral.getType().getId()); else throw new IllegalStateException("a double literal must have a datatype"); insertNode.setTimestamp(5, new Timestamp(doubleLiteral.getCreated().getTime()), calendarUTC); insertNode.executeUpdate(); } else if (node instanceof KiWiBooleanLiteral) { KiWiBooleanLiteral booleanLiteral = (KiWiBooleanLiteral) node; PreparedStatement insertNode = getPreparedStatement("store.bliteral"); insertNode.setLong(1, node.getId()); insertNode.setString(2, booleanLiteral.getContent()); insertNode.setBoolean(3, booleanLiteral.booleanValue()); if (booleanLiteral.getType() != null) insertNode.setLong(4, booleanLiteral.getType().getId()); else throw new IllegalStateException("a boolean literal must have a datatype"); insertNode.setTimestamp(5, new Timestamp(booleanLiteral.getCreated().getTime()), calendarUTC); insertNode.executeUpdate(); } else if (node instanceof KiWiStringLiteral) { KiWiStringLiteral stringLiteral = (KiWiStringLiteral) node; Double dbl_value = null; Long lng_value = null; if (stringLiteral.getContent().length() < 64 && NumberUtils.isNumber(stringLiteral.getContent())) try { dbl_value = Double.parseDouble(stringLiteral.getContent()); lng_value = Long.parseLong(stringLiteral.getContent()); } catch (NumberFormatException ex) { // ignore, keep NaN } PreparedStatement insertNode = getPreparedStatement("store.sliteral"); insertNode.setLong(1, node.getId()); insertNode.setString(2, stringLiteral.getContent()); if (dbl_value != null) { insertNode.setDouble(3, dbl_value); } else { insertNode.setObject(3, null); } if (lng_value != null) { insertNode.setLong(4, lng_value); } else { insertNode.setObject(4, null); } if (stringLiteral.getLocale() != null) { insertNode.setString(5, stringLiteral.getLocale().getLanguage().toLowerCase()); } else { insertNode.setObject(5, null); } if (stringLiteral.getType() != null) { insertNode.setLong(6, stringLiteral.getType().getId()); } else { insertNode.setObject(6, null); } insertNode.setTimestamp(7, new Timestamp(stringLiteral.getCreated().getTime()), calendarUTC); insertNode.executeUpdate(); } else { log.warn("unrecognized node type: {}", node.getClass().getCanonicalName()); } cacheNode(node); }