示例#1
0
 public static boolean setValue(
     PreparedStatement ps, int posicion, int tipo, String strDefault, String strValor) {
   try {
     if (strValor == null) {
       strValor = strDefault;
     }
     if (strValor != null) {
       if (strValor.compareTo("") == 0) ps.setNull(posicion, tipo);
       else {
         switch (tipo) {
           case 2:
             ps.setLong(posicion, Long.valueOf(strValor).longValue());
             break;
           case 12:
             ps.setString(posicion, strValor);
             break;
           case java.sql.Types.LONGVARCHAR:
             ps.setString(posicion, strValor);
             break;
           case 0:
             ps.setDouble(posicion, Double.valueOf(strValor).doubleValue());
             break;
         }
       }
     } else ps.setNull(posicion, tipo);
   } catch (Exception e) {
     e.printStackTrace();
     return (false);
   }
   return (true);
 }
 public void setString(Object ps, int param, String value) {
   try {
     if (getDatabaseAdapter().supportsOption(RDBMSAdapter.BLOB_SET_USING_SETSTRING)) {
       if (value == null) {
         if (column.isDefaultable() && column.getDefaultValue() != null) {
           ((PreparedStatement) ps).setString(param, column.getDefaultValue().toString().trim());
         } else {
           ((PreparedStatement) ps).setNull(param, getTypeInfo().getDataType());
         }
       } else {
         ((PreparedStatement) ps).setString(param, value);
       }
     } else {
       if (value == null) {
         if (column != null && column.isDefaultable() && column.getDefaultValue() != null) {
           ((PreparedStatement) ps)
               .setBlob(param, new BlobImpl(column.getDefaultValue().toString().trim()));
         } else {
           ((PreparedStatement) ps).setNull(param, getTypeInfo().getDataType());
         }
       } else {
         ((PreparedStatement) ps).setBlob(param, new BlobImpl(value));
       }
     }
   } catch (SQLException e) {
     throw new NucleusDataStoreException(
         LOCALISER_RDBMS.msg("055001", "String", "" + value, column, e.getMessage()), e);
   } catch (IOException e) {
     throw new NucleusDataStoreException(
         LOCALISER_RDBMS.msg("055001", "String", "" + value, column, e.getMessage()), e);
   }
 }
  @Override
  protected void setUpdateStatementValues(ChargeSession session, PreparedStatement ps)
      throws SQLException {
    // cols: auth_status = ?, xid = ?, ended = ?, posted = ?
    //       sessionid_hi, sessionid_lo
    ps.setString(1, session.getStatus() != null ? session.getStatus().toString() : null);
    if (session.getTransactionId() == null) {
      ps.setNull(2, Types.BIGINT);
    } else {
      ps.setLong(2, session.getTransactionId().longValue());
    }
    if (session.getEnded() != null) {
      // store ts in UTC time zone
      Calendar cal = calendarForDate(session.getEnded());
      Timestamp ts = new Timestamp(cal.getTimeInMillis());
      ps.setTimestamp(3, ts, cal);
    } else {
      ps.setNull(3, Types.TIMESTAMP);
    }
    if (session.getPosted() != null) {
      // store ts in UTC time zone
      Calendar cal = calendarForDate(session.getPosted());
      Timestamp ts = new Timestamp(cal.getTimeInMillis());
      ps.setTimestamp(4, ts, cal);
    } else {
      ps.setNull(4, Types.TIMESTAMP);
    }

    UUID pk = UUID.fromString(session.getSessionId());
    ps.setLong(5, pk.getMostSignificantBits());
    ps.setLong(6, pk.getLeastSignificantBits());
  }
 public void setString(PreparedStatement ps, int param, String value) {
   try {
     if (getDatastoreAdapter().supportsOption(DatastoreAdapter.BLOB_SET_USING_SETSTRING)) {
       if (value == null) {
         if (column.isDefaultable() && column.getDefaultValue() != null) {
           ps.setString(param, column.getDefaultValue().toString().trim());
         } else {
           ps.setNull(param, getJDBCType());
         }
       } else {
         ps.setString(param, value);
       }
     } else {
       if (value == null) {
         if (column != null && column.isDefaultable() && column.getDefaultValue() != null) {
           ps.setBlob(param, new BlobImpl(column.getDefaultValue().toString().trim()));
         } else {
           ps.setNull(param, getJDBCType());
         }
       } else {
         ps.setBlob(param, new BlobImpl(value));
       }
     }
   } catch (SQLException e) {
     throw new NucleusDataStoreException(
         Localiser.msg("055001", "String", "" + value, column, e.getMessage()), e);
   } catch (IOException e) {
     throw new NucleusDataStoreException(
         Localiser.msg("055001", "String", "" + value, column, e.getMessage()), e);
   }
 }
示例#5
0
 @Override
 public int findId(ApplicationInterface candidate) throws DAOException {
   int id = 0;
   PreparedStatement selectStmt;
   try {
     selectStmt = connection.prepareStatement(DB_QUERY_FIND_EXISITING);
     if (candidate.getMessageDigest(Digest.MD5) != null) {
       selectStmt.setString(1, candidate.getMessageDigest(Digest.MD5));
     } else {
       selectStmt.setNull(1, Types.VARCHAR);
     }
     if (candidate.getMessageDigest(Digest.SHA1) != null) {
       selectStmt.setString(2, candidate.getMessageDigest(Digest.SHA1));
     } else {
       selectStmt.setNull(2, Types.VARCHAR);
     }
     if (candidate.getMessageDigest(Digest.SHA256) != null) {
       selectStmt.setString(3, candidate.getMessageDigest(Digest.SHA256));
     } else {
       selectStmt.setNull(3, Types.VARCHAR);
     }
     ResultSet rs = selectStmt.executeQuery();
     if (rs.next()) {
       id = rs.getInt(DB_COLUMN_ID);
     }
   } catch (SQLException e) {
     throw new DAOException(e);
   }
   return id;
 }
 protected void addUserAuthorizations(
     String username, List<Authorization> authorizations, Connection conn) {
   PreparedStatement stat = null;
   try {
     stat = conn.prepareStatement(ADD_AUTHORIZATION);
     for (int i = 0; i < authorizations.size(); i++) {
       Authorization auth = authorizations.get(i);
       if (null == auth) continue;
       stat.setString(1, username);
       if (null != auth.getGroup()) {
         stat.setString(2, auth.getGroup().getName());
       } else {
         stat.setNull(2, Types.VARCHAR);
       }
       if (null != auth.getRole()) {
         stat.setString(3, auth.getRole().getName());
       } else {
         stat.setNull(3, Types.VARCHAR);
       }
       stat.addBatch();
       stat.clearParameters();
     }
     stat.executeBatch();
   } catch (Throwable t) {
     _logger.error("Error detected while addind user authorizations", t);
     throw new RuntimeException("Error detected while addind user authorizations", t);
   } finally {
     this.closeDaoResources(null, stat);
   }
 }
 /**
  * store
  *
  * @generated
  */
 public void store(EntityBean eb) throws Exception {
   Object objectTemp = null;
   TransactioncodeBean b = (TransactioncodeBean) eb;
   ie.ucd.srg.koa.kr.beans.TransactioncodeKey _primaryKey =
       new ie.ucd.srg.koa.kr.beans.TransactioncodeKey();
   _primaryKey.transactienummer = b.transactienummer;
   PreparedStatement pstmt;
   pstmt = getPreparedStatement(_storeString);
   try {
     if (_primaryKey.transactienummer == null) {
       pstmt.setNull(2, java.sql.Types.VARCHAR);
     } else {
       pstmt.setString(2, _primaryKey.transactienummer);
     }
     objectTemp =
         ie.ucd.srg.vap.converters.VapCharToBoolean.singleton()
             .dataFrom(new Boolean(b.alreadyused));
     if (objectTemp == null) {
       pstmt.setNull(1, java.sql.Types.CHAR);
     } else {
       pstmt.setString(1, (java.lang.String) objectTemp);
     }
     pstmt.executeUpdate();
   } finally {
     returnPreparedStatement(pstmt);
   }
 }
示例#8
0
 @Override
 protected void map(Project project, PreparedStatement stmt) throws SQLException {
   // id
   stmt.setInt(1, seq.get(Sequence.PROJECT, project.id));
   // ref_id
   stmt.setString(2, project.id);
   // name
   stmt.setString(3, project.name);
   // description
   stmt.setString(4, project.description);
   // f_category
   if (Category.isNull(project.categoryid)) stmt.setNull(5, java.sql.Types.INTEGER);
   else stmt.setInt(5, seq.get(Sequence.CATEGORY, project.categoryid));
   // creation_date
   stmt.setDate(6, project.creationdate);
   // functional_unit
   stmt.setString(7, project.functionalunit);
   // last_modification_date
   stmt.setDate(8, project.lastmodificationdate);
   // goal
   stmt.setString(9, project.goal);
   // f_author
   if (project.f_author == null) stmt.setNull(10, java.sql.Types.INTEGER);
   else stmt.setInt(10, seq.get(Sequence.ACTOR, project.f_author));
   // f_impact_method
   stmt.setNull(11, java.sql.Types.INTEGER);
   // f_nwset
   stmt.setNull(12, java.sql.Types.INTEGER);
   stmt.setLong(13, System.currentTimeMillis());
   stmt.setLong(14, 4294967296L);
 }
示例#9
0
 /**
  * Utility method for moving the contents of one of the parts into a prepared statement as a
  * string object.
  *
  * @param data Data connection object.
  * @param stmt Prepared statement
  * @param thisPage Object representing this request
  * @param position Position of the value in the prepared statement's argument list
  * @param element Name of the part in the multi-part form
  * @param convertFlag True means that value should be converted to upper case
  * @param SQLType Type of SQL column (Types.CHAR or Types.VARCHAR)
  * @throws SQLException if database errors
  */
 public void loadByteArray(
     DatabaseProperties data,
     PreparedStatement stmt,
     ThisPage thisPage,
     int position,
     String element,
     boolean convertFlag,
     int SQLType)
     throws SQLException {
   byte contents[] = null;
   Contents portion = thisPage.getElement(element);
   if (portion == null) {
     stmt.setNull(position, SQLType);
     return;
   }
   contents = thisPage.getElement(element).getContents();
   if (contents == null) {
     stmt.setNull(position, SQLType);
   } else if (contents.length == 0) {
     stmt.setNull(position, SQLType);
   } else {
     String working = new String(contents).trim();
     if (convertFlag) {
       working = working.toUpperCase();
     }
     if (working.length() == 0) {
       stmt.setNull(position, SQLType);
     } else {
       stmt.setString(position, working);
     }
   }
 }
示例#10
0
 private void addColumnMutation(
     String schemaName, String tableName, PColumn column, PreparedStatement colUpsert)
     throws SQLException {
   colUpsert.setString(1, schemaName);
   colUpsert.setString(2, tableName);
   colUpsert.setString(3, column.getName().getString());
   colUpsert.setString(
       4, column.getFamilyName() == null ? null : column.getFamilyName().getString());
   colUpsert.setInt(5, column.getDataType().getSqlType());
   colUpsert.setInt(
       6,
       column.isNullable() ? ResultSetMetaData.columnNullable : ResultSetMetaData.columnNoNulls);
   if (column.getMaxLength() == null) {
     colUpsert.setNull(7, Types.INTEGER);
   } else {
     colUpsert.setInt(7, column.getMaxLength());
   }
   if (column.getScale() == null) {
     colUpsert.setNull(8, Types.INTEGER);
   } else {
     colUpsert.setInt(8, column.getScale());
   }
   colUpsert.setInt(9, column.getPosition() + 1);
   colUpsert.setInt(10, ColumnModifier.toSystemValue(column.getColumnModifier()));
   colUpsert.execute();
 }
示例#11
0
  protected void setParameter(
      PreparedStatement ps, ParameterMapping mapping, Object[] parameters, int i)
      throws SQLException {
    Object value = parameters[i];
    // Apply Null Value
    String nullValueString = mapping.getNullValue();
    if (nullValueString != null) {
      TypeHandler handler = mapping.getTypeHandler();
      if (handler.equals(value, nullValueString)) {
        value = null;
      }
    }

    // Set Parameter
    TypeHandler typeHandler = mapping.getTypeHandler();
    if (value != null) {
      typeHandler.setParameter(ps, i + 1, value, mapping.getJdbcTypeName());
    } else if (typeHandler instanceof CustomTypeHandler) {
      typeHandler.setParameter(ps, i + 1, value, mapping.getJdbcTypeName());
    } else {
      int jdbcType = mapping.getJdbcType();
      if (jdbcType != JdbcTypeRegistry.UNKNOWN_TYPE) {
        ps.setNull(i + 1, jdbcType);
      } else {
        ps.setNull(i + 1, Types.OTHER);
      }
    }
  }
 /** findLocByUserProf */
 public EJSFinder findLocByUserProf(
     java.lang.String ardais_user_id, java.lang.String ardais_acct_key)
     throws javax.ejb.FinderException, java.rmi.RemoteException {
   ResultSet resultSet = null;
   PreparedStatement pstmt = null;
   try {
     preFind();
     pstmt =
         getPreparedStatement(
             " SELECT T1.ARDAIS_STAFF_ID, T1.ARDAIS_STAFF_LNAME, T1.ARDAIS_STAFF_FNAME, T1.ARDAIS_ACCT_KEY, T1.ARDAIS_USER_ID, T1.LOCATION_ADDRESS_ID FROM ILTDS_ARDAIS_STAFF  T1 WHERE ardais_user_id = ? and ardais_acct_key = ?");
     if (ardais_user_id == null) {
       pstmt.setNull(1, java.sql.Types.VARCHAR);
     } else {
       pstmt.setString(1, ardais_user_id);
     }
     if (ardais_acct_key == null) {
       pstmt.setNull(2, java.sql.Types.VARCHAR);
     } else {
       pstmt.setString(2, ardais_acct_key);
     }
     resultSet = pstmt.executeQuery();
     return new EJSJDBCFinder(resultSet, this, pstmt);
   } catch (Exception ex) {
     throw new EJSPersistenceException("find failed:", ex);
   }
 }
示例#13
0
  /**
   * Inserts a new instance of the data element. The store method needs to guarantee that the data
   * object is of type Committee.
   *
   * @param committee the instance to create. @ if there is a problem inserting.
   */
  protected void insert(Committee committee) {
    Connection conn = null;
    PreparedStatement ps = null;
    int id =
        (committee.isRemote())
            ? committee.getEntryId().intValue()
            : sequenceGenerator.getNextSequenceNumber("entry");
    try {

      conn = getDataSource().getConnection();
      ps = conn.prepareStatement(INSERT_QUERY);
      logService.debug("Preparing insert statement " + INSERT_QUERY);
      ps.setString(1, committee.getPersonId());
      ps.setInt(2, id);
      committee.setEntryId(String.valueOf(id));
      ps.setString(3, committee.getEntryName());
      if (committee.getFromDate() == null) ps.setNull(4, Types.TIMESTAMP);
      else ps.setTimestamp(4, new java.sql.Timestamp(committee.getFromDate().getTime()));
      if (committee.getToDate() == null) ps.setNull(5, Types.TIMESTAMP);
      else ps.setTimestamp(5, new java.sql.Timestamp(committee.getToDate().getTime()));
      ps.setString(6, committee.getDescription());
      int result = ps.executeUpdate();
      logService.debug("There were " + result + " rows inserted.");
    } catch (SQLException sqle) {
      throw new DataAccessException(sqle);
    } finally {
      close(conn, ps, null);
    }
  }
  /**
   * @param accession
   * @param taxonomyId
   * @param dbConnection
   * @throws Exception
   */
  public void saveOrUpdateOnAccession(LocalCache_Swiss_prot_DTO item, Connection dbConnection)
      throws Exception {

    PreparedStatement pstmt = null;

    // CREATE TABLE local_cache_swiss_prot_data (
    //		  accession VARCHAR(255) NOT NULL,
    //		  taxonomy_id INT NULL,

    final String sql =
        "INSERT INTO local_cache_swiss_prot_data (accession, taxonomy_id)"
            + " VALUES ( ?, ? ) ON DUPLICATE KEY UPDATE taxonomy_id = ?";

    try {

      pstmt = dbConnection.prepareStatement(sql);

      int counter = 0;

      counter++;
      pstmt.setString(counter, item.getAccession());

      counter++;
      if (item.getTaxonomyId() != null) {
        pstmt.setInt(counter, item.getTaxonomyId());
      } else {
        pstmt.setNull(counter, java.sql.Types.INTEGER);
      }

      counter++;
      if (item.getTaxonomyId() != null) {
        pstmt.setInt(counter, item.getTaxonomyId());
      } else {
        pstmt.setNull(counter, java.sql.Types.INTEGER);
      }

      pstmt.executeUpdate();

    } catch (Exception e) {

      String msg = "Failed to insert LocalCache_Swiss_prot_DTO, sql: " + sql;

      log.error(msg, e);

      throw e;

    } finally {

      // be sure database handles are closed

      if (pstmt != null) {
        try {
          pstmt.close();
        } catch (Throwable t) {;
        }
        pstmt = null;
      }
    }
  }
示例#15
0
  public void save(Iterable<Pessoa> data) throws SQLException, ParseException {

    try (PreparedStatement pstmt = this.conn.prepareStatement(QUERY_INSERT)) {

      try {

        conn.setAutoCommit(false);

        int batchSize = 0;

        for (Pessoa pessoa : data) {

          pstmt.setString(1, pessoa.getNome());

          pstmt.setString(2, pessoa.getCargo());

          if (pessoa.getDataNascimento() == null) {

            pstmt.setNull(3, Types.DATE);
          } else {
            pstmt.setDate(3, new Date(pessoa.getDataNascimento().getTime()));
          }

          if (pessoa.getCpf() == null) {

            pstmt.setNull(4, Types.BIGINT);
          } else {

            pstmt.setLong(4, pessoa.getCpf());
          }

          pstmt.addBatch();
          batchSize++;

          if (batchSize == this.chunkSize) {

            pstmt.executeBatch();
            batchSize = 0;
          }
        }

        /*
         * necessário, pois o driver do hsqldb lança exceção caso
         * seja chamado executeBatch sem nenhum addBatch antes
         */
        if (batchSize > 0) {

          pstmt.executeBatch();
        }

        conn.commit();

      } catch (SQLException e) {

        conn.rollback();
        throw e;
      }
    }
  }
  public void insertMessage(WebSocketMessageDTO message) throws DatabaseException {
    try {
      // synchronize on whole object to avoid race conditions with insertOrUpdateChannel()
      synchronized (this) {
        if (getConnection().isClosed()) {
          // temporarily buffer messages and write them the next time
          messagesBuffer.offer(message);
          return;
        }

        do {
          if (!channelIds.contains(message.channel.id)) {
            // maybe channel is buffered
            if (channelsBuffer.size() > 0) {
              insertOrUpdateChannel(channelsBuffer.poll());
            }
            throw new SQLException("channel not inserted: " + message.channel.id);
          }

          logger.info("insert message: " + message.toString());

          psInsertMessage.setInt(1, message.id);
          psInsertMessage.setInt(2, message.channel.id);
          psInsertMessage.setTimestamp(3, new Timestamp(message.timestamp));
          psInsertMessage.setInt(4, message.opcode);

          // write payload
          if (message.payload instanceof String) {
            psInsertMessage.setClob(5, new JDBCClob((String) message.payload));
            psInsertMessage.setNull(6, Types.BLOB);
          } else if (message.payload instanceof byte[]) {
            psInsertMessage.setNull(5, Types.CLOB);
            psInsertMessage.setBlob(6, new JDBCBlob((byte[]) message.payload));
          } else {
            throw new SQLException(
                "Attribute 'payload' of class WebSocketMessageDTO has got wrong type!");
          }

          psInsertMessage.setInt(7, message.payloadLength);
          psInsertMessage.setBoolean(8, message.isOutgoing);
          psInsertMessage.execute();

          if (message instanceof WebSocketFuzzMessageDTO) {
            WebSocketFuzzMessageDTO fuzzMessage = (WebSocketFuzzMessageDTO) message;
            psInsertFuzz.setInt(1, fuzzMessage.fuzzId);
            psInsertFuzz.setInt(2, fuzzMessage.id);
            psInsertFuzz.setInt(3, fuzzMessage.channel.id);
            psInsertFuzz.setString(4, fuzzMessage.state.toString());
            psInsertFuzz.setString(5, fuzzMessage.fuzz);
            psInsertFuzz.execute();
          }

          message = messagesBuffer.poll();
        } while (message != null);
      }
    } catch (SQLException e) {
      throw new DatabaseException(e);
    }
  }
示例#17
0
 /*
  * (non-Javadoc)
  *
  * @see de.rub.syssec.saaf.db.dao.GenericDAO#create(java.lang.Object)
  */
 @Override
 public int create(ApplicationInterface entity) throws DAOException, DuplicateEntityException {
   int id = 0;
   // parameter index in the prepared statement
   // using this idiom its easier to add new params
   int index = 0;
   try {
     PreparedStatement insert =
         connection.prepareStatement(DB_QUERY_INSERT, Statement.RETURN_GENERATED_KEYS);
     insert.setInt(++index, entity.getNumberOfCodelines(true)); // codelines
     insert.setInt(++index, entity.getAllSmaliClasss(true).size()); // classes
     insert.setString(++index, entity.getMessageDigest(Digest.MD5));
     insert.setString(++index, entity.getMessageDigest(Digest.SHA1));
     insert.setString(++index, entity.getMessageDigest(Digest.SHA256));
     insert.setString(++index, entity.getMessageDigest(Digest.FuzzyHash));
     insert.setString(++index, entity.getApplicationName()); // file_name
     if (entity.getManifest() != null) {
       insert.setInt(++index, entity.getManifest().getMinSdkVersion());
       insert.setInt(++index, entity.getManifest().getVersionCode());
       insert.setString(++index, entity.getManifest().getVersionName());
       insert.setString(++index, entity.getManifest().getAppLabel());
       insert.setString(++index, entity.getManifest().getAppLabelResolved());
       insert.setString(++index, entity.getManifest().getPackageName());
       insert.setBoolean(++index, entity.getManifest().isAppDebuggable());
       insert.setInt(++index, entity.getManifest().getActivities().size());
       insert.setInt(++index, entity.getManifest().getReceivers().size());
       insert.setInt(++index, entity.getManifest().getServices().size());
     } else {
       insert.setNull(++index, Types.INTEGER); // minsdkversion
       insert.setNull(++index, Types.INTEGER); // versioncode
       insert.setNull(++index, Types.VARCHAR); // VersionName
       insert.setNull(++index, Types.VARCHAR); // AppLabel
       insert.setNull(++index, Types.VARCHAR); // AppLabelResolved
       insert.setNull(++index, Types.VARCHAR); // PackageName
       insert.setNull(++index, Types.BOOLEAN); // AppDebuggable
       insert.setNull(++index, Types.INTEGER); // Activties
       insert.setNull(++index, Types.INTEGER); // Receivers
       insert.setNull(++index, Types.INTEGER); // Services
     }
     insert.executeUpdate();
     ResultSet rs = insert.getGeneratedKeys();
     if (rs.next()) {
       id = rs.getInt(1);
     } else {
       throw new DAOException("Generated keys could not be retrieved!");
     }
   } catch (SQLException e) {
     // use the SQL Error Code to throw specific exception for duplicate entries
     if (e.getSQLState().equalsIgnoreCase(SQL_ERROR_DUPLICATE)
         && e.getMessage().toLowerCase().contains("duplicate")) {
       throw new DuplicateEntityException(
           "An entity with the same key attributes already exists", e);
     } else {
       throw new DAOException(e);
     }
   }
   return id;
 }
  /** Inserts a new row in the project_phases table. */
  public ProjectPhasesPk insert(ProjectPhases dto) throws ProjectPhasesDaoException {
    long t1 = System.currentTimeMillis();
    // declare variables
    final boolean isConnSupplied = (userConn != null);
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;

    try {
      // get the user-specified connection or get a connection from the ResourceManager
      conn = isConnSupplied ? userConn : ResourceManager.getConnection();

      stmt = conn.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS);
      int index = 1;
      stmt.setInt(index++, dto.getIdprojectPhases());
      stmt.setString(index++, dto.getName());
      stmt.setString(index++, dto.getDescription());
      stmt.setDate(
          index++,
          dto.getStartDate() == null ? null : new java.sql.Date(dto.getStartDate().getTime()));
      stmt.setDate(
          index++, dto.getEndDate() == null ? null : new java.sql.Date(dto.getEndDate().getTime()));
      if (dto.isStatusNull()) {
        stmt.setNull(index++, java.sql.Types.INTEGER);
      } else {
        stmt.setInt(index++, dto.getStatus());
      }

      if (dto.isProjectIdNull()) {
        stmt.setNull(index++, java.sql.Types.INTEGER);
      } else {
        stmt.setInt(index++, dto.getProjectId());
      }

      System.out.println("Executing " + SQL_INSERT + " with DTO: " + dto);
      int rows = stmt.executeUpdate();
      long t2 = System.currentTimeMillis();
      System.out.println(rows + " rows affected (" + (t2 - t1) + " ms)");

      // retrieve values from auto-increment columns
      rs = stmt.getGeneratedKeys();
      if (rs != null && rs.next()) {
        dto.setIdprojectPhases(rs.getInt(1));
      }

      reset(dto);
      return dto.createPk();
    } catch (Exception _e) {
      _e.printStackTrace();
      throw new ProjectPhasesDaoException("Exception: " + _e.getMessage(), _e);
    } finally {
      ResourceManager.close(stmt);
      if (!isConnSupplied) {
        ResourceManager.close(conn);
      }
    }
  }
示例#19
0
  /*
   * (non-Javadoc)
   *
   * @see de.rub.syssec.saaf.db.dao.GenericDAO#update(java.lang.Object)
   */
  @Override
  public boolean update(ApplicationInterface entity) throws DAOException, NoSuchEntityException {
    boolean success = false;
    int recordsUpdated;
    int index = 0;
    PreparedStatement updateStmt;

    try {
      updateStmt = connection.prepareStatement(DB_QUERY_UDPATE);
      updateStmt.setInt(++index, entity.getNumberOfCodelines(true)); // codelines
      updateStmt.setInt(++index, entity.getAllSmaliClasss(true).size()); // classes
      updateStmt.setString(++index, entity.getMessageDigest(Digest.MD5));
      updateStmt.setString(++index, entity.getMessageDigest(Digest.SHA1));
      updateStmt.setString(++index, entity.getMessageDigest(Digest.SHA256));
      updateStmt.setString(++index, entity.getMessageDigest(Digest.FuzzyHash));
      updateStmt.setString(++index, entity.getApplicationName()); // file_name
      if (entity.getManifest() != null) {
        updateStmt.setInt(++index, entity.getManifest().getMinSdkVersion());
        updateStmt.setInt(++index, entity.getManifest().getVersionCode());
        updateStmt.setString(++index, entity.getManifest().getVersionName());
        updateStmt.setString(++index, entity.getManifest().getAppLabel());
        updateStmt.setString(++index, entity.getManifest().getAppLabelResolved());
        updateStmt.setString(++index, entity.getManifest().getPackageName());
        updateStmt.setBoolean(++index, entity.getManifest().isAppDebuggable());
        updateStmt.setInt(++index, entity.getManifest().getActivities().size());
        updateStmt.setInt(++index, entity.getManifest().getReceivers().size());
        updateStmt.setInt(++index, entity.getManifest().getServices().size());
      } else {
        updateStmt.setNull(++index, Types.INTEGER); // minsdkversion
        updateStmt.setNull(++index, Types.INTEGER); // versioncode
        updateStmt.setNull(++index, Types.VARCHAR); // VersionName
        updateStmt.setNull(++index, Types.VARCHAR); // AppLabel
        updateStmt.setNull(++index, Types.VARCHAR); // AppLabelResolved
        updateStmt.setNull(++index, Types.VARCHAR); // PackageName
        updateStmt.setNull(++index, Types.BOOLEAN); // AppDebuggable
        updateStmt.setNull(++index, Types.INTEGER); // Activties
        updateStmt.setNull(++index, Types.INTEGER); // Receivers
        updateStmt.setNull(++index, Types.INTEGER); // Services
      }
      updateStmt.setInt(++index, entity.getId()); // id
      recordsUpdated = updateStmt.executeUpdate();
      // this should affect at most one record
      if (recordsUpdated == 0) {
        throw new NoSuchEntityException();
      } else if (recordsUpdated == 1) {
        success = true;
      } else {
        // the update affected multiple records this should not happen!
        throw new DAOException(
            "Update of one entity affected multiple records. This should not happen!");
      }
    } catch (SQLException e) {
      throw new DAOException(e);
    }
    return success;
  }
 /**
  * Utility method for setting parameters in Prepared Statements.
  *
  * <p>For VARCHAR data types.
  *
  * @param stmt PreparedStatement object
  * @param location Number of parameter
  * @param value Value to be loaded in parameter
  * @throws SQLException
  */
 protected void loadVarchar(PreparedStatement stmt, int location, String value)
     throws SQLException {
   if (value == null) {
     stmt.setNull(location, Types.VARCHAR);
   } else if (value.trim().length() == 0) {
     stmt.setNull(location, Types.VARCHAR);
   } else {
     stmt.setString(location, value);
   }
 }
  public boolean delete() {
    PreparedStatement pstmt = null;

    if (!mflag) {
      con = DBConnPool.getConnection();
    }

    try {
      pstmt =
          con.prepareStatement("DELETE FROM LEDAdSource WHERE  ProductCode = ? AND SiteCode = ?");
      if (this.getProductCode() == null || this.getProductCode().equals("null")) {
        pstmt.setNull(1, 12);
      } else {
        pstmt.setString(1, this.getProductCode());
      }
      if (this.getSiteCode() == null || this.getSiteCode().equals("null")) {
        pstmt.setNull(2, 12);
      } else {
        pstmt.setString(2, this.getSiteCode());
      }
      pstmt.executeUpdate();
      pstmt.close();
    } catch (Exception ex) {
      // @@错误处理
      this.mErrors.copyAllErrors(db.mErrors);
      CError tError = new CError();
      tError.moduleName = "LEDAdSourceDB";
      tError.functionName = "delete()";
      tError.errorMessage = ex.toString();
      this.mErrors.addOneError(tError);

      try {
        pstmt.close();
      } catch (Exception e) {
      }

      if (!mflag) {
        try {
          con.close();
        } catch (Exception e) {
        }
      }

      return false;
    }

    if (!mflag) {
      try {
        con.close();
      } catch (Exception e) {
      }
    }

    return true;
  }
示例#22
0
  private PreparedStatement buildStatement(
      Scenario scenario,
      List<Column> columns,
      PreparedStatement statement,
      SimpleDateFormat simpleDateFormat)
      throws Exception {
    int count = 1;
    for (Column column : columns) {

      DataValue dataValue = getRulesApplier().getDataForRule(scenario, column);
      switch (column.getType()) {
        case VARCHAR:
          if (dataValue.getValue().equals("")) {
            statement.setNull(count, Types.VARCHAR);
          } else {
            statement.setString(count, dataValue.getValue());
          }
          break;
        case CHAR:
          if (dataValue.getValue().equals("")) {
            statement.setNull(count, Types.CHAR);
          } else {
            statement.setString(count, dataValue.getValue());
          }
          break;
        case DECIMAL:
          if (dataValue.getValue().equals("")) {
            statement.setNull(count, Types.DECIMAL);
          } else {
            statement.setBigDecimal(count, new BigDecimal(dataValue.getValue()));
          }
          break;
        case INTEGER:
          if (dataValue.getValue().equals("")) {
            statement.setNull(count, Types.INTEGER);
          } else {
            statement.setInt(count, Integer.parseInt(dataValue.getValue()));
          }
          break;
        case DATE:
          if (dataValue.getValue().equals("")) {
            statement.setNull(count, Types.DATE);
          } else {
            Date date = new java.sql.Date(simpleDateFormat.parse(dataValue.getValue()).getTime());
            statement.setDate(count, date);
          }
          break;
        default:
          break;
      }
      count++;
    }
    return statement;
  }
示例#23
0
  /**
   * Creates the entity in the database if it does not exist in the database (this is the case if it was constructed using {@link RelationManager#newCourseElement} rather than {@link RelationManager#createCourseElement).
   */
  @Override
  public CourseElement create() throws de.fu.weave.orm.DatabaseException {
    String query =
        "INSERT INTO "
            + "\"scetris\".\"CourseElement\""
            + " (\"name\", \"part_of\", \"duration\", \"type\", \"required\", \"timekey\")"
            + " VALUES (?, ?, ?, ?, ?, ?) RETURNING id;";
    timekey(true);
    try {
      java.sql.PreparedStatement stmt =
          manager.connectionManager().getConnection().prepareStatement(query);
      int i = 1;
      if (_name != null) {
        stmt.setString(i++, _name);
      } else {
        stmt.setNull(i++, java.sql.Types.VARCHAR);
      }

      stmt.setInt(i++, ref_partOf);

      stmt.setInt(i++, _duration);

      if (ref_type != null) {
        stmt.setInt(i++, ref_type);
      } else {
        stmt.setNull(i++, java.sql.Types.INTEGER);
      }

      if (manager.isNull(_required)) {
        stmt.setBoolean(i++, _required = true);
      } else {
        stmt.setBoolean(i++, _required);
      }

      stmt.setTimestamp(i++, _timekey);
      java.sql.ResultSet keys = manager.executeQuery(stmt);
      if (keys.next()) {
        _id = keys.getInt(1);
      } else {
        throw new de.fu.weave.orm.DatabaseException("no key was generated. phail.");
      }
      changed_name = false;
      changed_partOf = false;
      changed_duration = false;
      changed_type = false;
      changed_required = false;

    } catch (java.sql.SQLException e) {
      throw new de.fu.weave.orm.DatabaseException(query, e);
    }
    exists = true;
    return this;
  }
示例#24
0
 @Override
 public void traceMarker() throws Exception {
   PreparedStatement preparedStatement =
       connection.prepareStatement("insert into employee values (?, ?)");
   try {
     preparedStatement.setNull(1, Types.VARCHAR);
     preparedStatement.setNull(2, Types.BINARY);
     preparedStatement.execute();
   } finally {
     preparedStatement.close();
   }
 }
  /**
   * Inserts the supplied ExtraForm data submission into the extra-form table.
   *
   * <p>Will go through the ExtraForm.Data objects and inject the values into the the
   * PreparedStatement according to the data type (INT, DECIMAL, etc.).
   *
   * @param extraForm Object that contains the extra-form submission information that should be
   *     inserted into the extra-form table
   * @param query SQL INSERT statement with placeholders for the PreparedStatement
   * @throws ConstraintViolations if extra-form data could not be inserted
   * @see ExtraForm.Data
   */
  private void insertData(ExtraForm extraForm, String query) throws ConstraintViolations {
    try (Connection connection = dataSource.getConnection();
        PreparedStatement pstmt = connection.prepareStatement(query); ) {
      int pointer = 1;
      for (ExtraForm.Data d : extraForm.getData()) {
        if (d.value == null || d.value.length() == 0) {

          String type = d.type;

          if (type.equalsIgnoreCase("STRING")) {
            //						typeName = "VARCHAR";
            type = "TEXT";
          } else if (type.equalsIgnoreCase("JRDATE")) {
            type = "DATETIME";
          } else if (type.equalsIgnoreCase("JRDATETIME")) {
            type = "DATETIME";
          } else if (type.equalsIgnoreCase("SELECTN") || type.equalsIgnoreCase("SELECT1")) {
            type = "TEXT";
          } else if (type.equalsIgnoreCase("INTEGER")) {
            type = "INT";
          }

          if (type.equalsIgnoreCase("INT")) {
            pstmt.setNull(pointer, java.sql.Types.INTEGER);
          } else if (type.equalsIgnoreCase("DECIMAL")) {
            pstmt.setNull(pointer, java.sql.Types.DECIMAL);
          } else if (type.equalsIgnoreCase("DATETIME")) {
            pstmt.setNull(pointer, java.sql.Types.DATE);
          } else if (type.equalsIgnoreCase("VARCHAR")) {
            pstmt.setNull(pointer, java.sql.Types.VARCHAR);
          } else {
            pstmt.setString(pointer, d.value);
          }
        } else {
          if ((d.type.equalsIgnoreCase("INTEGER") || d.type.equalsIgnoreCase("INT"))
              && d.value.equals("null")) {
            pstmt.setNull(pointer, java.sql.Types.INTEGER);
          } else pstmt.setString(pointer, d.value);
        }
        pointer++;
      }
      int rowCount = pstmt.executeUpdate();
    } catch (SQLException e) {
      if (e instanceof SQLIntegrityConstraintViolationException) {
        throw new ConstraintViolations(e.getMessage());
      } else {
        throw new ConstraintViolations(e.getMessage());
      }
    } catch (Exception e) {
      throw new ConstraintViolations(e.getMessage());
    }
  }
 /*
  * (non-Javadoc)
  *
  * @see net.sf.hibernate.UserType#nullSafeSet(java.sql.PreparedStatement,
  *      java.lang.Object, int)
  */
 public void nullSafeSet(PreparedStatement st, Object value, int index)
     throws HibernateException, SQLException {
   if (value == null) {
     st.setNull(index, Types.VARCHAR);
   } else {
     ContainerTypeAttribute attribute = (ContainerTypeAttribute) value;
     if (attribute.getContainerType() != null) {
       st.setString(index, attribute.getContainerType().getDbValue());
     } else {
       st.setNull(index, Types.VARCHAR);
     }
   }
 }
 public void setStatementParameters(PreparedStatement ps) throws SQLException {
   ps.setString(1, scan_rs_id.toString());
   ps.setString(2, scan_object_name);
   ps.setString(3, scan_object_type);
   ps.setString(4, scan_type);
   ps.setString(5, isolation_level);
   if (no_visited_pages != null) ps.setInt(6, no_visited_pages.intValue());
   else ps.setNull(6, Types.INTEGER);
   if (no_visited_rows != null) ps.setInt(7, no_visited_rows.intValue());
   else ps.setNull(7, Types.INTEGER);
   if (no_qualified_rows != null) ps.setInt(8, no_qualified_rows.intValue());
   else ps.setNull(8, Types.INTEGER);
   if (no_visited_deleted_rows != null) ps.setInt(9, no_visited_deleted_rows.intValue());
   else ps.setNull(9, Types.INTEGER);
   if (no_fetched_columns != null) ps.setInt(10, no_fetched_columns.intValue());
   else ps.setNull(10, Types.INTEGER);
   ps.setString(11, bitset_of_fetched_columns);
   if (btree_height != null) ps.setInt(12, btree_height.intValue());
   else ps.setNull(12, Types.INTEGER);
   if (fetch_size != null) ps.setInt(13, fetch_size.intValue());
   else ps.setNull(13, Types.INTEGER);
   ps.setString(14, start_position);
   ps.setString(15, stop_position);
   ps.setString(16, scan_qualifiers);
   ps.setString(17, next_qualifiers);
   ps.setString(18, hash_key_column_numbers);
   if (hash_table_size != null) ps.setInt(19, hash_table_size.intValue());
   else ps.setNull(19, Types.INTEGER);
 }
示例#28
0
 public static void insertIntoPaperTradesTable(PaperTrade paperTrade) {
   PreparedStatement pstmt = null;
   try {
     pstmt =
         DBopsMySql.setuptradesConnection()
             .prepareStatement(
                 "INSERT INTO `PaperTrades` "
                     + "(`id`, `EnteredInDB`, `BeginTradeDateTime`, `symbol`, `Position`, "
                     + "`entry`, `stop loss`, `stop risk`, `Stop profit`, "
                     + "`profitpotential`, `Outcome`, `ExitTradeDateTime`) "
                     + "VALUES (NULL, CURRENT_TIMESTAMP, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
     // BeginTradeDateTime
     if (paperTrade.getBeginTradeDateTime() == null) {
       pstmt.setNull(1, Types.DATE);
     } else {
       pstmt.setTimestamp(1, paperTrade.getBeginTradeTimestamp());
     }
     // symbol
     if (paperTrade.getSymbol() == null) {
       pstmt.setNull(2, Types.VARCHAR);
     } else {
       pstmt.setString(2, paperTrade.getSymbol());
     }
     // Position
     if (paperTrade.getPosition() == null) {
       pstmt.setNull(3, Types.VARCHAR);
     } else {
       pstmt.setString(3, paperTrade.getPosition());
     }
     // entry
     pstmt.setDouble(4, paperTrade.getEntry());
     // stop loss
     pstmt.setDouble(5, paperTrade.getStopLoss());
     // stop risk
     pstmt.setDouble(6, paperTrade.getStopRisk());
     // Stop profit
     pstmt.setDouble(7, paperTrade.getProfitStop());
     // profitpotential
     pstmt.setDouble(8, paperTrade.getProfitpotential());
     // Outcome
     pstmt.setDouble(9, paperTrade.getOutcome());
     // ExitTradeDateTime
     pstmt.setTimestamp(10, paperTrade.getExitTradeTimestamp());
     pstmt.execute();
     pstmt.close();
   } catch (SQLException ex) {
     MsgBox.err2(ex);
   } finally {
   }
 }
示例#29
0
 public String updateImport(PreparedStatement pstmt) {
   String msg = "";
   try {
     int jj = 1;
     if (device_id.equals("")) pstmt.setNull(jj++, Types.INTEGER);
     else pstmt.setString(jj++, device_id);
     if (name.equals("")) pstmt.setNull(jj++, Types.VARCHAR);
     else pstmt.setString(jj++, name);
     if (serial_num.equals("")) pstmt.setNull(jj++, Types.VARCHAR);
     else pstmt.setString(jj++, serial_num);
     if (model.equals("")) pstmt.setNull(jj++, Types.VARCHAR);
     else pstmt.setString(jj++, model);
     if (type.equals("")) pstmt.setNull(jj++, Types.VARCHAR);
     else pstmt.setString(jj++, type);
     if (vertical_resolution.equals("")) pstmt.setNull(jj++, Types.INTEGER);
     else pstmt.setString(jj++, vertical_resolution);
     if (horizontal_resolution.equals("")) pstmt.setNull(jj++, Types.VARCHAR);
     else pstmt.setString(jj++, horizontal_resolution);
     if (manufacturer.equals("")) pstmt.setNull(jj++, Types.VARCHAR);
     else pstmt.setString(jj++, manufacturer);
     pstmt.setString(jj++, external_id);
     pstmt.executeUpdate();
   } catch (Exception ex) {
     msg += "update " + ex;
     logger.error(external_id + " " + ex);
     // System.err.println(id+" "+ex);
   }
   return msg;
 }
  public boolean alterar(MateriaPrima materiaPrima) throws Exception {
    boolean status = false;

    // string query do banco
    String sql =
        " UPDATE materiaprima SET codigo=?, nome=?, estoque=?, unidade=?, fabricacao=?,"
            + " vencimento=?, descricao=? where id=?";
    PreparedStatement ps = null;

    // chama uma instância da Connection e tenta realizar uma conexão com o banco através do
    // AutoCloseable
    try (Connection conn = ConnectionProvider.getInstance().getConnection()) {
      // seta os atributos do objeto matéria-prima, fazendo a alteração.
      ps = conn.prepareStatement(sql);
      ps.setString(1, materiaPrima.getCodigo());
      ps.setString(2, materiaPrima.getNome());
      ps.setDouble(3, materiaPrima.getEstoque());
      ps.setLong(4, materiaPrima.getUnidade());

      if (materiaPrima.getFabricacao() != null) {
        ps.setDate(5, Date.valueOf(materiaPrima.getFabricacao()));
      } else {
        ps.setNull(5, Types.DATE);
      }

      if (materiaPrima.getVencimento() != null) {
        ps.setDate(6, Date.valueOf(materiaPrima.getVencimento()));
      } else {
        ps.setNull(6, Types.DATE);
      }

      ps.setString(7, materiaPrima.getDescricao());
      ps.setLong(8, materiaPrima.getId());

      if (ps.executeUpdate() != 0) {
        status = true;
      }

      // fecha as conexões
      ps.close();
      conn.close();
    }
    // trata, caso de uma exceção
    catch (SQLException e) {
      System.out.println("Erro ao alterar a materiaPrima\n" + e);
    }
    // retorna true ou false, dizendo se o metodo foi executado com sucesso.
    return status;
  }