List of usage examples for java.sql PreparedStatement getGeneratedKeys
ResultSet getGeneratedKeys() throws SQLException;
Statement
object. From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java
private long insertAndGetConnectorId(MConnector mc, Connection conn) { PreparedStatement baseConnectorStmt = null; try {//from w w w.j a v a 2 s . co m baseConnectorStmt = conn.prepareStatement(STMT_INSERT_INTO_CONFIGURABLE, Statement.RETURN_GENERATED_KEYS); baseConnectorStmt.setString(1, mc.getUniqueName()); baseConnectorStmt.setString(2, mc.getClassName()); baseConnectorStmt.setString(3, mc.getVersion()); baseConnectorStmt.setString(4, mc.getType().name()); int baseConnectorCount = baseConnectorStmt.executeUpdate(); if (baseConnectorCount != 1) { throw new SqoopException(DerbyRepoError.DERBYREPO_0012, Integer.toString(baseConnectorCount)); } ResultSet rsetConnectorId = baseConnectorStmt.getGeneratedKeys(); if (!rsetConnectorId.next()) { throw new SqoopException(DerbyRepoError.DERBYREPO_0013); } // connector configurable also have directions insertConnectorDirections(rsetConnectorId.getLong(1), mc.getSupportedDirections(), conn); return rsetConnectorId.getLong(1); } catch (SQLException ex) { throw new SqoopException(DerbyRepoError.DERBYREPO_0014, mc.toString(), ex); } finally { closeStatements(baseConnectorStmt); } }
From source file:org.wso2.carbon.repository.core.jdbc.dao.JDBCResourceDAO.java
public void addProperties(ResourceImpl resource) throws RepositoryException { JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection(); String sql1, sql2, sql3;/*from w w w . j av a2s . co m*/ boolean isVersioningProperties = StaticConfiguration.isVersioningProperties(); sql1 = "INSERT INTO REG_PROPERTY (REG_NAME, REG_VALUE, REG_TENANT_ID) VALUES (?, ?, ?)"; sql2 = "SELECT MAX(REG_ID) FROM REG_PROPERTY"; if (isVersioningProperties) { sql3 = "INSERT INTO REG_RESOURCE_PROPERTY (REG_PROPERTY_ID, REG_VERSION, REG_TENANT_ID) VALUES (?, ?, ?)"; } else { sql3 = "INSERT INTO REG_RESOURCE_PROPERTY (REG_PROPERTY_ID, REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID) VALUES (?, ?, ?, ?)"; } ResourceIDImpl resourceID = resource.getResourceIDImpl(); for (Object nameObj : resource.getPropertyKeys()) { String name = (String) nameObj; List propValues = (List) resource.getPropertyValues(name); if (propValues != null) { for (Object valueObj : propValues) { PreparedStatement ps1 = null; PreparedStatement ps2 = null; PreparedStatement ps3 = null; ResultSet resultSet1 = null; try { String value = (String) valueObj; String dbProductName = conn.getMetaData().getDatabaseProductName(); boolean returnsGeneratedKeys = DBUtils.canReturnGeneratedKeys(dbProductName); if (returnsGeneratedKeys) { ps1 = conn.prepareStatement(sql1, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, DatabaseConstants.ID_FIELD) }); } else { ps1 = conn.prepareStatement(sql1); } ps3 = conn.prepareStatement(sql3); // prepare to execute query1 for the property ps1.setString(1, name); ps1.setString(2, value); ps1.setInt(3, CurrentContext.getTenantId()); if (returnsGeneratedKeys) { ps1.executeUpdate(); resultSet1 = ps1.getGeneratedKeys(); } else { synchronized (ADD_PROPERTY_LOCK) { ps1.executeUpdate(); ps2 = conn.prepareStatement(sql2); resultSet1 = ps2.executeQuery(); } } if (resultSet1.next()) { // setting the property id int propertyId = resultSet1.getInt(1); ps3.setInt(1, propertyId); if (isVersioningProperties) { ps3.setLong(2, resource.getVersionNumber()); ps3.setInt(3, CurrentContext.getTenantId()); } else { ps3.setLong(2, resourceID.getPathID()); if (resourceID.getName() == null) { ps3.setNull(3, Types.VARCHAR); } else { ps3.setString(3, resourceID.getName()); } ps3.setInt(4, CurrentContext.getTenantId()); } ps3.executeUpdate(); } } catch (SQLException e) { String msg = "Failed to add properties to the resource " + resource.getPath() + ". " + e.getMessage(); log.error(msg, e); throw new RepositoryDBException(msg, e); } finally { // closing prepared statements before moving on to next iteration try { try { try { if (resultSet1 != null) { resultSet1.close(); } } finally { if (ps1 != null) { ps1.close(); } } } finally { try { if (ps2 != null) { ps2.close(); } } finally { if (ps3 != null) { ps3.close(); } } } } catch (SQLException ex) { String msg = InternalConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR; log.error(msg, ex); } } } } } }
From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java
/** * Pre-register HDFS Connector so that config upgrade will work. * NOTE: This should be used only in the upgrade path *///from www . j a v a 2 s . c om @Deprecated protected long registerHdfsConnector(Connection conn) { if (LOG.isTraceEnabled()) { LOG.trace("Begin HDFS Connector pre-loading."); } List<URL> connectorConfigs = ConnectorManagerUtils.getConnectorConfigs(); if (LOG.isInfoEnabled()) { LOG.info("Connector configs: " + connectorConfigs); } ConnectorHandler handler = null; for (URL url : connectorConfigs) { handler = new ConnectorHandler(url); if (handler.getConnectorConfigurable().getPersistenceId() != -1) { return handler.getConnectorConfigurable().getPersistenceId(); } PreparedStatement baseConnectorStmt = null; if (handler.getUniqueName().equals(CONNECTOR_HDFS)) { try { baseConnectorStmt = conn.prepareStatement( STMT_INSERT_INTO_CONNECTOR_WITHOUT_SUPPORTED_DIRECTIONS, Statement.RETURN_GENERATED_KEYS); baseConnectorStmt.setString(1, handler.getConnectorConfigurable().getUniqueName()); baseConnectorStmt.setString(2, handler.getConnectorConfigurable().getClassName()); baseConnectorStmt.setString(3, "0"); if (baseConnectorStmt.executeUpdate() == 1) { ResultSet rsetConnectorId = baseConnectorStmt.getGeneratedKeys(); if (rsetConnectorId.next()) { if (LOG.isInfoEnabled()) { LOG.info("HDFS Connector pre-loaded: " + rsetConnectorId.getLong(1)); } return rsetConnectorId.getLong(1); } } } catch (SQLException e) { throw new SqoopException(DerbyRepoError.DERBYREPO_0013); } finally { closeStatements(baseConnectorStmt); } break; } } return -1L; }
From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java
/** * Create an HDFS connection ( used only in version 2). * Intended to be used when moving HDFS connector out of the sqoop driver * to its own connector./*from w w w .j a v a 2 s . co m*/ * * NOTE: Should be used only in the upgrade path! */ @Deprecated private Long createHdfsConnection(Connection conn, Long connectorId) { if (LOG.isTraceEnabled()) { LOG.trace("Creating HDFS link."); } PreparedStatement stmt = null; int result; try { stmt = conn.prepareStatement(STMT_INSERT_CONNECTION, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, CONNECTOR_HDFS); stmt.setLong(2, connectorId); stmt.setBoolean(3, true); stmt.setNull(4, Types.VARCHAR); stmt.setTimestamp(5, new Timestamp(System.currentTimeMillis())); stmt.setNull(6, Types.VARCHAR); stmt.setTimestamp(7, new Timestamp(System.currentTimeMillis())); result = stmt.executeUpdate(); if (result != 1) { throw new SqoopException(DerbyRepoError.DERBYREPO_0003, Integer.toString(result)); } ResultSet rsetConnectionId = stmt.getGeneratedKeys(); if (!rsetConnectionId.next()) { throw new SqoopException(DerbyRepoError.DERBYREPO_0004); } if (LOG.isTraceEnabled()) { LOG.trace("Created HDFS connection."); } return rsetConnectionId.getLong(1); } catch (SQLException ex) { throw new SqoopException(DerbyRepoError.DERBYREPO_0005, ex); } finally { closeStatements(stmt); } }
From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCResourceDAO.java
public void addProperties(ResourceImpl resource) throws RegistryException { JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection(); String sql1, sql2, sql3;/*from w ww. j a va 2 s .co m*/ boolean isVersioningProperties = StaticConfiguration.isVersioningProperties(); sql1 = "INSERT INTO REG_PROPERTY (REG_NAME, REG_VALUE, REG_TENANT_ID) VALUES (?, ?, ?)"; sql2 = "SELECT MAX(REG_ID) FROM REG_PROPERTY"; if (isVersioningProperties) { sql3 = "INSERT INTO REG_RESOURCE_PROPERTY (REG_PROPERTY_ID, REG_VERSION, " + "REG_TENANT_ID) VALUES (?, ?, ?)"; } else { sql3 = "INSERT INTO REG_RESOURCE_PROPERTY (REG_PROPERTY_ID, REG_PATH_ID, " + "REG_RESOURCE_NAME, REG_TENANT_ID) VALUES (?, ?, ?, ?)"; } ResourceIDImpl resourceID = resource.getResourceIDImpl(); Properties props = resource.getProperties(); if (props != null) { for (Object nameObj : props.keySet()) { String name = (String) nameObj; List propValues = (List) props.get(name); if (propValues != null) { for (Object valueObj : propValues) { PreparedStatement ps1 = null; PreparedStatement ps2 = null; PreparedStatement ps3 = null; ResultSet resultSet1 = null; try { String value = (String) valueObj; String dbProductName = conn.getMetaData().getDatabaseProductName(); boolean returnsGeneratedKeys = DBUtils.canReturnGeneratedKeys(dbProductName); if (returnsGeneratedKeys) { ps1 = conn.prepareStatement(sql1, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, DatabaseConstants.ID_FIELD) }); } else { ps1 = conn.prepareStatement(sql1); } ps3 = conn.prepareStatement(sql3); // prepare to execute query1 for the property ps1.setString(1, name); ps1.setString(2, value); ps1.setInt(3, CurrentSession.getTenantId()); if (returnsGeneratedKeys) { ps1.executeUpdate(); resultSet1 = ps1.getGeneratedKeys(); } else { synchronized (ADD_PROPERTY_LOCK) { ps1.executeUpdate(); ps2 = conn.prepareStatement(sql2); resultSet1 = ps2.executeQuery(); } } if (resultSet1.next()) { // setting the property id int propertyId = resultSet1.getInt(1); ps3.setInt(1, propertyId); if (isVersioningProperties) { ps3.setLong(2, resource.getVersionNumber()); ps3.setInt(3, CurrentSession.getTenantId()); } else { ps3.setLong(2, resourceID.getPathID()); if (resourceID.getName() == null) { ps3.setNull(3, Types.VARCHAR); } else { ps3.setString(3, resourceID.getName()); } ps3.setInt(4, CurrentSession.getTenantId()); } ps3.executeUpdate(); } } catch (SQLException e) { String msg = "Failed to add properties to the resource " + resource.getPath() + ". " + e.getMessage(); log.error(msg, e); throw new RegistryException(msg, e); } finally { // closing prepared statements before moving on to next iteration try { try { try { if (resultSet1 != null) { resultSet1.close(); } } finally { if (ps1 != null) { ps1.close(); } } } finally { try { if (ps2 != null) { ps2.close(); } } finally { if (ps3 != null) { ps3.close(); } } } } catch (SQLException ex) { String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR; log.error(msg, ex); } } } } } } }
From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java
/** * Register configs in derby database. This method will insert the ids * generated by the repository into the configs passed in itself. * * Use given prepared statements to create entire config structure in database. * * @param configurableId/*from w w w. j av a 2s .c om*/ * @param configs * @param type * @param baseConfigStmt * @param baseInputStmt * @param conn * @return short number of configs registered. * @throws SQLException */ private short registerConfigs(Long configurableId, Direction direction, List<MConfig> configs, String type, PreparedStatement baseConfigStmt, PreparedStatement baseInputStmt, Connection conn) throws SQLException { short configIndex = 0; for (MConfig config : configs) { if (configurableId == null) { baseConfigStmt.setNull(1, Types.BIGINT); } else { baseConfigStmt.setLong(1, configurableId); } baseConfigStmt.setString(2, config.getName()); baseConfigStmt.setString(3, type); baseConfigStmt.setShort(4, configIndex++); int baseConfigCount = baseConfigStmt.executeUpdate(); if (baseConfigCount != 1) { throw new SqoopException(DerbyRepoError.DERBYREPO_0015, Integer.toString(baseConfigCount)); } ResultSet rsetConfigId = baseConfigStmt.getGeneratedKeys(); if (!rsetConfigId.next()) { throw new SqoopException(DerbyRepoError.DERBYREPO_0016); } long configId = rsetConfigId.getLong(1); config.setPersistenceId(configId); if (direction != null) { registerConfigDirection(configId, direction, conn); } // Insert all the inputs List<MInput<?>> inputs = config.getInputs(); registerConfigInputs(configId, inputs, baseInputStmt); } return configIndex; }
From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java
/** * {@inheritDoc}//from w ww. ja v a 2 s . co m */ @Override public void createLink(MLink link, Connection conn) { PreparedStatement stmt = null; int result; try { stmt = conn.prepareStatement(STMT_INSERT_LINK, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, link.getName()); stmt.setLong(2, link.getConnectorId()); stmt.setBoolean(3, link.getEnabled()); stmt.setString(4, link.getCreationUser()); stmt.setTimestamp(5, new Timestamp(link.getCreationDate().getTime())); stmt.setString(6, link.getLastUpdateUser()); stmt.setTimestamp(7, new Timestamp(link.getLastUpdateDate().getTime())); result = stmt.executeUpdate(); if (result != 1) { throw new SqoopException(DerbyRepoError.DERBYREPO_0012, Integer.toString(result)); } ResultSet rsetConnectionId = stmt.getGeneratedKeys(); if (!rsetConnectionId.next()) { throw new SqoopException(DerbyRepoError.DERBYREPO_0013); } long connectionId = rsetConnectionId.getLong(1); createInputValues(STMT_INSERT_LINK_INPUT, connectionId, link.getConnectorLinkConfig().getConfigs(), conn); link.setPersistenceId(connectionId); } catch (SQLException ex) { logException(ex, link); throw new SqoopException(DerbyRepoError.DERBYREPO_0019, ex); } finally { closeStatements(stmt); } }
From source file:com.krawler.esp.servlets.AdminServlet.java
public static String createAnnouncementsForUser(Connection conn, HttpServletRequest request, String companyid, String loginid) throws ServiceException { PreparedStatement pstmt = null; ResultSet rs = null;/*w w w . j av a 2 s.com*/ int index = -1; String announcement = StringUtil.serverHTMLStripper(request.getParameter("announcement").toString()); String fromdate = StringUtil.serverHTMLStripper(request.getParameter("fromdate").toString()); String todate = StringUtil.serverHTMLStripper(request.getParameter("todate").toString()); companyid = StringUtil.serverHTMLStripper(companyid); if (StringUtil.isNullOrEmpty(announcement) || StringUtil.isNullOrEmpty(fromdate) || StringUtil.isNullOrEmpty(todate) || StringUtil.isNullOrEmpty(companyid)) { return KWLErrorMsgs.errProccessingData; } String buf = StringUtil.serverHTMLStripper(request.getParameter("featureid").toString()); if (StringUtil.isNullOrEmpty(buf)) { buf = companyid; } String[] userid = buf.split(","); try { // fromdate = Timezone.toCompanyTimezone(conn, fromdate,companyid); // todate = Timezone.toCompanyTimezone(conn, todate,companyid); pstmt = conn.prepareStatement("INSERT INTO announcements (announceval, `from`, `to`) VALUES (?, ?, ?)"); pstmt.setString(1, announcement); pstmt.setString(2, fromdate); pstmt.setString(3, todate); pstmt.executeUpdate(); rs = pstmt.getGeneratedKeys(); rs.next(); index = rs.getInt(1); if (index != -1) { for (int cnt = 0; cnt < userid.length; cnt++) { pstmt = conn.prepareStatement( "INSERT INTO userannouncements (userid, announceid, companyid) VALUES (?,?,?)"); pstmt.setString(1, userid[cnt]); pstmt.setInt(2, index); pstmt.setString(3, companyid); pstmt.executeUpdate(); } } } catch (SQLException e) { throw ServiceException.FAILURE("Admin.createAnnouncementsForUser", e); } finally { DbPool.closeStatement(pstmt); } return "true"; }
From source file:oscar.form.FrmONAREnhancedRecord.java
int addRecord(Properties props, String table, List<String> namesA, Integer id) throws SQLException { StringBuilder sb = new StringBuilder(); sb.append("INSERT INTO " + table + " ("); for (String name : namesA) { sb.append(name.split("\\|")[0] + ","); }/* w ww .j a v a 2s . c om*/ sb.deleteCharAt(sb.length() - 1); sb.append(") VALUES ("); for (String name : namesA) { sb.append("?,"); } sb.deleteCharAt(sb.length() - 1); sb.append(");"); PreparedStatement preparedStmt = null; try { preparedStmt = DbConnectionFilter.getThreadLocalDbConnection().prepareStatement(sb.toString(), Statement.RETURN_GENERATED_KEYS); for (int x = 0; x < namesA.size(); x++) { String t = namesA.get(x); String theName = t.split("\\|")[0]; String type = t.split("\\|")[1]; if (theName.equals("ID")) { if (id == null) { preparedStmt.setNull(x + 1, Types.INTEGER); } else { preparedStmt.setInt(x + 1, id.intValue()); } continue; } if (type.equals("VARCHAR") || type.equals("CHAR")) { String value = props.getProperty(theName); if (value == null) { preparedStmt.setNull(x + 1, getType(type)); } else { preparedStmt.setString(x + 1, value); } } else if (type.equals("INT") || type.equals("TINYINT")) { String value = props.getProperty(theName); if (value != null && value.isEmpty()) { MiscUtils.getLogger().info("empty value for " + theName); } if (value == null || value.isEmpty()) { value = "0"; } else if (value.equalsIgnoreCase("on") || value.equalsIgnoreCase("checked='checked'")) { value = "1"; } preparedStmt.setInt(x + 1, Integer.parseInt(value)); } else if (type.equals("DATE")) { String value = props.getProperty(theName); Date d = null; if (theName.equalsIgnoreCase("formEdited")) { d = new Date(); } else { if ((value == null) || (value.indexOf('/') != -1)) d = UtilDateUtilities.StringToDate(value, dateFormat); else d = UtilDateUtilities.StringToDate(value, _newDateFormat); } if (d == null) preparedStmt.setNull(x + 1, Types.DATE); else preparedStmt.setDate(x + 1, new java.sql.Date(d.getTime())); } else if (type.equals("TIMESTAMP")) { Date d; if (theName.equalsIgnoreCase("formEdited")) { d = new Date(); } else { d = UtilDateUtilities.StringToDate(props.getProperty(theName), "yyyyMMddHHmmss"); } if (d == null) preparedStmt.setNull(x + 1, Types.TIMESTAMP); else preparedStmt.setTimestamp(x + 1, new java.sql.Timestamp(d.getTime())); } else { MiscUtils.getLogger().error("missing type handler for this column " + theName, new Exception()); } } preparedStmt.executeUpdate(); if (id == null) { ResultSet rs = null; try { rs = preparedStmt.getGeneratedKeys(); if (rs.next()) { id = rs.getInt(1); } } finally { if (rs != null) rs.close(); } } } finally { if (preparedStmt != null) { preparedStmt.close(); } } return id; }
From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java
/** * {@inheritDoc}//w w w . j a v a2 s. c om */ @Override public void createJob(MJob job, Connection conn) { PreparedStatement stmt = null; int result; try { stmt = conn.prepareStatement(STMT_INSERT_JOB, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, job.getName()); stmt.setLong(2, job.getLinkId(Direction.FROM)); stmt.setLong(3, job.getLinkId(Direction.TO)); stmt.setBoolean(4, job.getEnabled()); stmt.setString(5, job.getCreationUser()); stmt.setTimestamp(6, new Timestamp(job.getCreationDate().getTime())); stmt.setString(7, job.getLastUpdateUser()); stmt.setTimestamp(8, new Timestamp(job.getLastUpdateDate().getTime())); result = stmt.executeUpdate(); if (result != 1) { throw new SqoopException(DerbyRepoError.DERBYREPO_0012, Integer.toString(result)); } ResultSet rsetJobId = stmt.getGeneratedKeys(); if (!rsetJobId.next()) { throw new SqoopException(DerbyRepoError.DERBYREPO_0013); } long jobId = rsetJobId.getLong(1); // from config for the job createInputValues(STMT_INSERT_JOB_INPUT, jobId, job.getJobConfig(Direction.FROM).getConfigs(), conn); // to config for the job createInputValues(STMT_INSERT_JOB_INPUT, jobId, job.getJobConfig(Direction.TO).getConfigs(), conn); // driver config per job createInputValues(STMT_INSERT_JOB_INPUT, jobId, job.getDriverConfig().getConfigs(), conn); job.setPersistenceId(jobId); } catch (SQLException ex) { logException(ex, job); throw new SqoopException(DerbyRepoError.DERBYREPO_0026, ex); } finally { closeStatements(stmt); } }