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);
   }
 }
 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);
   }
 }
  public void testBlobA() {

    try {
      String ddl0 = "DROP TABLE BLOBTEST IF EXISTS";
      String ddl1 = "CREATE TABLE BLOBTEST(ID IDENTITY, BLOBFIELD BLOB(1000))";

      statement.execute(ddl0);
      statement.execute(ddl1);
    } catch (SQLException e) {
      e.printStackTrace();
    }

    try {
      String dml0 = "insert into blobtest(blobfield) values(?)";
      String dql0 = "select * from blobtest;";
      PreparedStatement ps = connection.prepareStatement(dml0);
      byte[] data = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
      Blob blob = new JDBCBlob(data);

      ps.setBlob(1, blob);
      ps.executeUpdate();

      data[4] = 50;
      blob = new JDBCBlob(data);

      ps.setBlob(1, blob);
      ps.executeUpdate();
      ps.close();

      ps = connection.prepareStatement(dql0);

      ResultSet rs = ps.executeQuery();

      rs.next();

      Blob blob1 = rs.getBlob(2);

      rs.next();

      Blob blob2 = rs.getBlob(2);
      byte[] data1 = blob1.getBytes(1, 10);
      byte[] data2 = blob2.getBytes(1, 10);

      assertTrue(data1[4] == 5 && data2[4] == 50);
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
Beispiel #4
0
 @Override
 public void inserir(Editora editora) {
   Connection conexao = connectionFactory.conectar();
   String sql = "INSERT INTO tbEditora(cnpj, nome, logo) " + "VALUES (?,?,?)";
   PreparedStatement ps = null;
   try {
     ps = conexao.prepareStatement(sql);
     ps.setString(1, editora.getCnpj());
     ps.setString(2, editora.getNome());
     ps.setBlob(3, editora.getLogoBlob());
     ps.executeUpdate();
     ps.close();
     conexao.close();
   } catch (SQLException e) {
     e.printStackTrace();
     throw new RuntimeException(e.getMessage());
   } finally {
     try {
       ps.close();
       conexao.close();
     } catch (SQLException e) {
       e.printStackTrace();
     }
   }
 }
Beispiel #5
0
  @Override
  public void atualizar(Editora editora) {
    System.out.println(editora.getCnpj());
    Connection conexao = connectionFactory.conectar();
    String sql = "UPDATE tbEditora " + "SET cnpj=?, nome=?, logo=? WHERE cnpj=?";
    PreparedStatement ps = null;
    try {
      ps = conexao.prepareStatement(sql);
      ps.setString(1, editora.getCnpj());
      ps.setString(2, editora.getNome());
      ps.setBlob(3, editora.getLogoBlob());
      ps.setString(4, editora.getCnpj());
      ps.executeUpdate();
      ps.close();
      conexao.close();

    } catch (SQLException e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage());
    } finally {
      try {
        ps.close();
        conexao.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
  @Override
  public boolean editTenant(TenantBean tenant, String fname, String lname) {

    try {
      Connector c = new Connector();
      Connection connection = c.getConnection();

      String query =
          "update tenant set image = ?, contact = ?, gender = ?, address = ?, degree = ?, school = ?, expectedyearofgrad = ?, status=? where fname = ? and lname = ? ";
      PreparedStatement ps = connection.prepareStatement(query);
      ps.setBlob(1, tenant.getImage());
      ps.setDouble(2, tenant.getContact());
      ps.setString(3, tenant.getGender());
      ps.setString(4, tenant.getAddress());
      ps.setString(5, tenant.getDegree());
      ps.setString(6, tenant.getSchool());
      ps.setInt(7, tenant.getExpectedyearofgrad());
      ps.setBoolean(8, tenant.getStatus());
      ps.setString(9, fname);
      ps.setString(10, lname);
      ps.executeUpdate();

      return true;
    } catch (SQLException ex) {
      Logger.getLogger(TenantDAOImplementation.class.getName()).log(Level.SEVERE, null, ex);
    }

    return false;
  }
  @Override
  public boolean addTenant(TenantBean tenant) { // important
    try {
      Connector c = new Connector();
      Connection connection = c.getConnection();
      String query =
          "insert into tenant (tenantID, fname, lname, image, contact, gender, address, degree, school, expectedyearofgrad, status)"
              + " values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
      PreparedStatement ps = connection.prepareStatement(query);
      ps.setInt(1, tenant.getTenantID());
      ps.setString(2, tenant.getFname());
      ps.setString(3, tenant.getLname());
      ps.setBlob(4, tenant.getImage());
      // ps.setLong(5, 639166267392L);
      ps.setLong(5, tenant.getContact());
      ps.setString(6, tenant.getGender());
      ps.setString(7, tenant.getAddress());
      ps.setString(8, tenant.getDegree());
      ps.setString(9, tenant.getSchool());
      ps.setInt(10, tenant.getExpectedyearofgrad());
      ps.setBoolean(11, tenant.getStatus());
      ps.executeUpdate();
      connection.close();

      return true;
    } catch (SQLException ex) {
      Logger.getLogger(TenantDAOImplementation.class.getName()).log(Level.SEVERE, null, ex);
    }

    return false;
  }
  private void testBlob(int length) throws Exception {
    Random r = new Random(length);
    byte[] data = new byte[length];
    r.nextBytes(data);
    Blob b = conn.createBlob();
    OutputStream out = b.setBinaryStream(1);
    out.write(data, 0, data.length);
    out.close();
    stat.execute("delete from test");

    PreparedStatement prep = conn.prepareStatement("insert into test values(?, ?)");
    prep.setInt(1, 1);
    prep.setBlob(2, b);
    prep.execute();

    prep.setInt(1, 2);
    b = conn.createBlob();
    b.setBytes(1, data);
    prep.setBlob(2, b);
    prep.execute();

    prep.setInt(1, 3);
    prep.setBlob(2, new ByteArrayInputStream(data));
    prep.execute();

    prep.setInt(1, 4);
    prep.setBlob(2, new ByteArrayInputStream(data), -1);
    prep.execute();

    ResultSet rs;
    rs = stat.executeQuery("select * from test");
    rs.next();
    Blob b2 = rs.getBlob(2);
    assertEquals(length, b2.length());
    byte[] bytes = b.getBytes(1, length);
    byte[] bytes2 = b2.getBytes(1, length);
    assertEquals(bytes, bytes2);
    rs.next();
    b2 = rs.getBlob(2);
    assertEquals(length, b2.length());
    bytes2 = b2.getBytes(1, length);
    assertEquals(bytes, bytes2);
    while (rs.next()) {
      bytes2 = rs.getBytes(2);
      assertEquals(bytes, bytes2);
    }
  }
  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);
    }
  }
  private static int writeBlobToDb(Connection conn, Long id, Blob dataBlob) throws Exception {
    String sql = "update client_image set contents = ? where image_id = ?";
    PreparedStatement pst = conn.prepareStatement(sql);
    pst.setBlob(1, dataBlob);
    pst.setLong(2, id);

    return pst.executeUpdate();
  }
 public void setBlob(int i, Blob x) throws SQLException {
   checkOpen();
   try {
     _stmt.setBlob(i, x);
   } catch (SQLException e) {
     handleException(e);
   }
 }
 public void setBlob(int idx, Blob blob) throws SQLException {
   try {
     addMementoEntry("setBlob", new Class[] {Blob.class}, idx, blob);
     wrapped.setBlob(idx, blob);
   } catch (SQLException e) {
     throw new UcanaccessSQLException(e);
   }
 }
 public void setBlob(int idx, InputStream is, long length) throws SQLException {
   try {
     addMementoEntry("setBlob", new Class[] {InputStream.class, Long.TYPE}, idx, is, length);
     wrapped.setBlob(idx, is, length);
   } catch (SQLException e) {
     throw new UcanaccessSQLException(e);
   }
 }
  public void setBlob(int i, Blob x) throws SQLException {
    Profiler profiler = _profilerPoint.start();

    try {
      _preparedStatement.setBlob(i, x);
    } finally {
      profiler.finish();
    }
  }
 public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
   String methodCall = "setBlob(" + parameterIndex + ", " + inputStream + ")";
   argTraceSet(parameterIndex, "(InputStream)", "<InputStream>");
   try {
     realPreparedStatement.setBlob(parameterIndex, inputStream);
   } catch (SQLException s) {
     reportException(methodCall, s);
     throw s;
   }
   reportReturn(methodCall);
 }
 public void setBlob(int i, Blob x) throws SQLException {
   String methodCall = "setBlob(" + i + ", " + x + ")";
   argTraceSet(i, "(Blob)", x == null ? null : ("<Blob of size " + x.length() + ">"));
   try {
     realPreparedStatement.setBlob(i, x);
   } catch (SQLException s) {
     reportException(methodCall, s);
     throw s;
   }
   reportReturn(methodCall);
 }
  @Override
  public void updateBarang(barang barang) throws BarangException {
    PreparedStatement statement = null;
    try {
      connection.setAutoCommit(false);
      statement = connection.prepareStatement(updateBarang);
      statement.setString(1, barang.getIdBarang());
      statement.setString(2, barang.getIdBarcode());
      statement.setString(3, barang.getNamaBarang());
      statement.setString(4, barang.getTipe());
      statement.setString(5, barang.getMerek());
      statement.setInt(6, barang.getHargamodal());
      statement.setInt(7, barang.getEceran());
      statement.setInt(8, barang.getGrosir());
      statement.setString(9, barang.getSatuan());
      statement.setInt(10, barang.getStok());
      statement.setInt(11, barang.getStokMinimum());
      statement.setString(12, barang.getSupplier());
      statement.setString(13, barang.getKeterangan());
      try {
        statement.setBlob(14, new FileInputStream(barang.getGambar()));
      } catch (FileNotFoundException ex) {
        Logger.getLogger(ReminderDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
      }
      statement.setString(14, barang.getKategori());
      statement.executeUpdate();
      connection.commit();
    } catch (SQLException exception) {
      try {
        connection.rollback();
      } catch (SQLException ex) {

      }
      JOptionPane.showMessageDialog(null, "Insert barang gagal karena " + exception);
    } finally {
      try {
        connection.setAutoCommit(true);
      } catch (SQLException ex) {
      }
      if (statement != null) {
        try {
          statement.close();
        } catch (SQLException exception) {

        }
      }
    }
  }
  public void test_blob_Blob_String() throws Exception {
    Connection conn = getConnection();

    declareAndRunFunction("blob_Blob_String", "blob", new String[] {"varchar( 10 )"}, "'3'", "33");

    // now test blob arguments
    declareFunction(conn, "varchar_Blob_Blob", "varchar( 10 )", new String[] {"blob"});

    runFunction(conn, "varchar_Blob_Blob", " \"blob_Blob_String\"( 'abc' )", "abc", null);

    // make sure that you can set lob-typed ? parameters
    PreparedStatement ps = chattyPrepare(conn, "values ( \"varchar_Blob_Blob\"( ? ) )");
    String expectedValue = "34";
    Blob blob = AnsiSignatures.blob_Blob_String(expectedValue);
    ps.setBlob(1, blob);
    String actualValue = getScalarString(ps);
    assertTrue(expectedValue.equals(actualValue));
  }
  /**
   * This method is used for editing the details on songs
   *
   * @param s The song that is being changed, the details are changed on the command and updated
   *     here
   * @return An integer value indicating errors or success
   */
  @Override
  public int editDetails(Song s) {
    if (s != null) {
      Connection con = null;
      PreparedStatement ps = null;

      try {
        con = getConnection();
        Blob art = con.createBlob();
        art.setBytes(1, s.getArtwork());
        String query =
            "UPDATE "
                + TABLE_NAME
                + "SET "
                + FILENAME
                + " = ?,"
                + TITLE
                + " = ?,"
                + ARTIST
                + " = ?,"
                + ALBUM
                + " = ?,"
                + GENRE
                + " = ?,"
                + YEAR
                + " = ?,"
                + PRICE
                + " = ?,"
                + LICENSE
                + " = ?,"
                + ARTWORK
                + " = ?"
                + " WHERE "
                + SONGID
                + " = ?";
        ps = con.prepareStatement(query);
        ps.setString(1, s.getFilename());
        ps.setString(2, s.getTitle());
        ps.setString(3, s.getArtist());
        ps.setString(4, s.getAlbum());
        ps.setString(5, s.getGenre());
        ps.setInt(6, s.getYear());
        ps.setDouble(7, s.getPrice());
        ps.setString(8, s.getLicense());
        ps.setBlob(9, art);
        ps.setInt(10, s.getSongId());
        int result = ps.executeUpdate();

        if (result > 0) return SUCCESS;
      } catch (SQLException ex2) {
        if (DEBUG) ex2.printStackTrace();
      } finally {
        try {
          if (ps != null) ps.close();
          if (con != null) freeConnection(con);
        } catch (SQLException e) {
          if (DEBUG) e.printStackTrace();
        }
      }
    }
    return OTHER;
  }
 public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
   delegate.setBlob(parameterIndex, inputStream);
 }
  // this method is a work in progress. additional functionality will be added as needed.
  private int setPreparedStatementParameter(Object object, int index) {

    if ((preparedStatement_ == null) || (preparedStatementParameters_ == null)) {
      logger.warn(
          "Can't set preparedStatementParameters - preparedStatementParameters or preparedStatement is null");
      return -1;
    }

    try {
      if (object == null) {
        preparedStatement_.setObject(index++, null);
      } else if (object instanceof BigDecimal) {
        preparedStatement_.setBigDecimal(index++, (BigDecimal) object);
      } else if (object instanceof Blob) {
        preparedStatement_.setBlob(index++, (Blob) object);
      } else if (object instanceof Boolean) {
        preparedStatement_.setBoolean(index++, (Boolean) object);
      } else if (object instanceof Byte) {
        preparedStatement_.setByte(index++, (Byte) object);
      } else if (object instanceof byte[]) {
        preparedStatement_.setBytes(index++, (byte[]) object);
      } else if (object instanceof Clob) {
        preparedStatement_.setClob(index++, (Clob) object);
      } else if (object instanceof Double) {
        preparedStatement_.setDouble(index++, (Double) object);
      } else if (object instanceof Float) {
        preparedStatement_.setFloat(index++, (Float) object);
      } else if (object instanceof Integer) {
        preparedStatement_.setInt(index++, (Integer) object);
      } else if (object instanceof List) {
        for (Object listObject : (List) object) {
          setPreparedStatementParameter(listObject, index++);
        }
      } else if (object instanceof Long) {
        preparedStatement_.setLong(index++, (Long) object);
      } else if (object instanceof Short) {
        preparedStatement_.setShort(index++, (Short) object);
      } else if (object instanceof String) {
        preparedStatement_.setString(index++, (String) object);
      } else if (object instanceof java.sql.Timestamp) {
        preparedStatement_.setTimestamp(index++, (java.sql.Timestamp) object);
      } else if (object instanceof java.sql.Date) {
        preparedStatement_.setDate(index++, (java.sql.Date) object);
      } else if (object instanceof java.util.Date) {
        java.util.Date tempDate = (java.util.Date) object;
        java.sql.Date dateSql = new java.sql.Date(tempDate.getTime());
        preparedStatement_.setDate(index++, dateSql);
      } else {
        if (object instanceof Object) {
        } else {
          logger.warn(
              "Setting PreparedStatement parameter to 'object' type when object is not an object type");
        }

        preparedStatement_.setObject(index++, object);
      }

      return index;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return -1;
    }
  }
  public boolean newEvent(
      Part filepart,
      String title,
      String description,
      String location,
      String startdate,
      String enddate,
      int points,
      int theme)
      throws IOException {

    InputStream inputStream = null;
    int length = 0;
    String type = null;

    if (filepart != null) {
      // prints out some information for debugging
      length = (int) filepart.getSize();
      type = filepart.getContentType();
      // obtains input stream of the upload file
      inputStream = filepart.getInputStream();
    }

    Connection con = null;
    try {

      Class.forName("com.mysql.jdbc.Driver").newInstance();
      con =
          DriverManager.getConnection("jdbc:mysql://160.153.16.42:3306/Enterprise_Gym", user, pass);

      PreparedStatement ps2 = null;

      String sqlOption =
          "INSERT INTO event (title,description,location,date,end_date,theme_idtheme,points,image,image_length,image_type) VALUES (?,?,?,?,?,?,?,?,?,?)";
      ps2 = con.prepareStatement(sqlOption);
      ps2.setString(1, title);
      ps2.setString(2, description);
      ps2.setString(3, location);
      ps2.setString(4, startdate);
      ps2.setString(5, enddate);
      ps2.setInt(6, theme);
      ps2.setInt(7, points);
      if (inputStream != null) {
        // fetches input stream of the upload file for the blob column
        ps2.setBlob(8, inputStream);
        ps2.setInt(9, length);
        ps2.setString(10, type);
      }
      ps2.executeUpdate();

      // Find out the id of the new account to insert into user.

      con.close();

      return true;

    } catch (Exception e) {
      System.out.println("connection to db failed");
      e.printStackTrace();
      return false;
    }
  }
 public void setBlob(int parameterIndex, Blob x) throws SQLException {
   delegate.setBlob(parameterIndex, x);
 }
 @Override
 public void setBlob(int parameterIndex, InputStream x, long length) throws SQLException {
   stmt.setBlob(parameterIndex, x, length);
   logValue(parameterIndex, x == null ? null : "<Blob>");
 }
  public boolean updateEvent(
      Part filepart,
      String title,
      String description,
      String location,
      String startdate,
      String enddate,
      int points,
      int theme,
      int id)
      throws IOException {

    InputStream inputStream = null;
    int length = 0;
    String type = null;

    if (filepart != null) {
      // prints out some information for debugging
      length = (int) filepart.getSize();
      type = filepart.getContentType();
      // obtains input stream of the upload file
      inputStream = filepart.getInputStream();
    }

    Connection con = null;

    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      con =
          DriverManager.getConnection("jdbc:mysql://160.153.16.42:3306/Enterprise_Gym", user, pass);
      if (inputStream != null && length != 0) {
        PreparedStatement ps = null;
        String sqlOption2 =
            "UPDATE event SET title=?,description=?,date=?,end_date=?,location=?,points=?,theme_idtheme=?,image=?,image_length=?,image_type=? WHERE idevent=?";
        ps = con.prepareStatement(sqlOption2);

        ps.setString(1, title);
        ps.setString(2, description);

        // fetches input stream of the upload file for the blob column
        ps.setString(3, startdate);
        ps.setString(4, enddate);
        ps.setString(5, location);
        ps.setInt(6, points);
        ps.setInt(7, theme);
        ps.setBlob(8, inputStream);
        ps.setInt(9, length);
        ps.setString(10, type);

        ps.setInt(11, id);
        ps.executeUpdate();

        return true;
      } else {
        PreparedStatement ps = null;
        String sqlOption2 =
            "UPDATE event SET title=?,description=?,date=?,end_date=?,location=?,points=?,theme_idtheme=? WHERE idevent=?";
        ps = con.prepareStatement(sqlOption2);

        ps.setString(1, title);
        ps.setString(2, description);

        // fetches input stream of the upload file for the blob column
        ps.setString(3, startdate);
        ps.setString(4, enddate);
        ps.setString(5, location);
        ps.setInt(6, points);
        ps.setInt(7, theme);
        ps.setInt(8, id);
        ps.executeUpdate();
        return true;
      }
    } catch (ClassNotFoundException
        | InstantiationException
        | IllegalAccessException
        | SQLException e) {
      System.out.println("expection thrown");
      System.out.println("false, exception");
      e.printStackTrace();
      return false;
    }
  }
 public void setParameter(PreparedStatement stmt, Object[] args) throws SQLException {
   stmt.setBlob((Integer) args[0], (Blob) args[1]);
 }
Beispiel #27
0
  public static void main(String[] args) {

    try {
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      ;
      Connection conn =
          DriverManager.getConnection(
              "jdbc:oracle:thin:@192.168.117.110:1521:WFZF", "qzkj", "qzkj");
      conn.setAutoCommit(false);
      ;

      BLOB blob = null;

      PreparedStatement pstmt =
          conn.prepareStatement("insert into sys_file(uuid,content,name) values(?,empty_blob(),?)");
      String uuid = Tool.getStringUUid();
      pstmt.setString(1, uuid);
      pstmt.setString(2, "test.flv");
      pstmt.executeUpdate();
      pstmt.close();

      pstmt = conn.prepareStatement("select content from sys_file where uuid= ? for update");
      pstmt.setString(1, uuid);
      ResultSet rset = pstmt.executeQuery();
      ;
      if (rset.next()) blob = (BLOB) rset.getBlob(1);
      ;

      String fileName = "test.flv";
      File f =
          new File(
              "C://Documents and Settings//Administrator//桌面//FlvPlayer201002//FlvPlayer201002//"
                  + fileName);
      FileInputStream fin = new FileInputStream(f);
      ;
      System.out.println("file size = " + fin.available());

      pstmt = conn.prepareStatement("update sys_file set content=? where uuid=?");
      ;

      OutputStream out = blob.getBinaryOutputStream();
      ;

      int count = -1, total = 0;
      byte[] data = new byte[(int) fin.available()];
      fin.read(data);
      ;
      out.write(data);
      ;
      /*
      byte[] data = new byte[blob.getBufferSize();];  另一种实现方法,节省内存
      while ((count = fin.read(data);); != -1); {
        total += count;
        out.write(data, 0, count);;
      }
      */

      fin.close();
      ;
      out.close();
      ;

      pstmt.setBlob(1, blob);
      ;
      pstmt.setString(2, uuid);

      pstmt.executeUpdate();
      ;
      pstmt.close();
      ;

      conn.commit();
      ;
      conn.close();
      ;
    } catch (SQLException e) {
      System.err.println(e.getMessage());
      ;
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println(e.getMessage());
      ;
    }
  }
  /**
   * This method is used for adding a new song to the database
   *
   * @param s The song you wish to add to the database
   * @return SUCCESS if it successfully inserted, otherwise OTHER
   */
  @Override
  public int addNewSong(Song s) {
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
      con = getConnection();
      Blob data = con.createBlob();
      Blob art = con.createBlob();
      try {
        if (s.getSongdata() != null) data.setBytes(1, s.getSongdata());
        if (s.getArtwork() != null) art.setBytes(1, s.getArtwork());
      } catch (Exception e) {
        if (DEBUG) e.printStackTrace();
      }
      String query =
          "INSERT INTO "
              + TABLE_NAME
              + " ("
              + FILENAME
              + ", "
              + TITLE
              + ", "
              + ARTIST
              + ", "
              + ALBUM
              + ", "
              + GENRE
              + ", "
              + YEAR
              + ", "
              + DURATION
              + ", "
              + PRICE
              + ", "
              + LICENSE
              + ", "
              + PLAYCOUNT
              + ", "
              + UPLOADDATE
              + ", "
              + ARTWORK
              + ", "
              + SONGDATA
              + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
      ps = con.prepareStatement(query);
      ps.setString(1, s.getFilename());
      ps.setString(2, s.getTitle());
      ps.setString(3, s.getArtist());
      ps.setString(4, s.getAlbum());
      ps.setString(5, s.getGenre());
      ps.setInt(6, s.getYear());
      ps.setInt(7, s.getDuration());
      ps.setDouble(8, s.getPrice());
      ps.setString(9, s.getLicense());
      ps.setInt(10, s.getPlayCount());
      ps.setDate(11, s.getUploaded());
      ps.setBlob(12, art);
      ps.setBlob(13, data);
      if (ps.executeUpdate() > 0) return SUCCESS; // It successfully inserted into the database
    } catch (SQLException e) {
      if (DEBUG) e.printStackTrace();
    } finally {
      try {
        if (rs != null) rs.close();
        if (ps != null) ps.close();
        if (con != null) freeConnection(con);
      } catch (SQLException e) {
        if (DEBUG) e.printStackTrace();
        return SQLEX;
      }
    }
    return OTHER;
  }
 @Override
 public void setBlob(int parameterIndex, Blob x) throws SQLException {
   stmt.setBlob(parameterIndex, x);
   logValue(parameterIndex, x == null ? null : "<Blob>");
 }
 public void setBlob(int i, Blob x) throws SQLException {
   saveParam(i, "" + x, "Blob");
   statement.setBlob(i, x);
 }