Example #1
1
  /**
   * Tests the implementation of getCharacterStream(long pos, long length).
   *
   * @throws Exception
   */
  public void testGetCharacterStreamLong() throws Exception {
    String str1 = "This is a test String. This is a test String";

    Reader r1 = new java.io.StringReader(str1);

    PreparedStatement ps = prepareStatement("insert into BLOBCLOB(ID, CLOBDATA) values(?,?)");
    int id = BlobClobTestSetup.getID();
    ps.setInt(1, id);
    ps.setCharacterStream(2, r1);
    ps.execute();
    ps.close();

    Statement st = createStatement();

    ResultSet rs = st.executeQuery("select CLOBDATA from " + "BLOBCLOB where ID=" + id);
    rs.next();
    Clob clob = rs.getClob(1);

    Reader r_1 = clob.getCharacterStream(2L, 5L);
    String str2 = str1.substring(1, 6);
    Reader r_2 = new java.io.StringReader(str2);

    assertEquals(r_2, r_1);

    rs.close();
    st.close();
  }
Example #2
0
  @Override
  public int update(Object obj) {
    int result = 0;

    try {
      conn.setAutoCommit(false);

      pstmt =
          conn.prepareStatement(
              "update THEME_MESSAGE set NAME=?,EMAIL=?,IMAGE=?,TITLE=? "
                  + "where THEME_MESSAGE_ID=?");
      pstmt =
          conn.prepareStatement("update THEME_CONTENT set CONTENT=? " + "where THEME_MESSAGE_ID=?");

      pstmt.setString(1, bean.getName());
      pstmt.setString(2, bean.getEmail());
      pstmt.setString(3, bean.getImage());
      pstmt.setString(4, bean.getTitle());
      pstmt.setInt(5, bean.getId());
      pstmt.executeUpdate();

      pstmt.setCharacterStream(1, null);
      pstmt.setInt(2, bean.getId());
      pstmt.executeUpdate();

      conn.commit();
    } catch (SQLException ex) {
      ex.printStackTrace();
      System.out.println("업데이트 에러");
    } finally {

    }

    return result;
  }
Example #3
0
 @Override
 public void generateParameter(PreparedStatement insertStatement) throws SQLException {
   Random rand = new Random();
   int length = rand.nextInt(MAX_LENGTH);
   char[] buffer = new char[(int) length];
   for (int i = 0; i < buffer.length; ++i) buffer[i] = (char) (rand.nextInt(26) + 'a');
   insertStatement.setCharacterStream(position, new CharArrayReader(buffer), (int) length);
 }
 public void setCharacterStream(int parameterIndex, java.io.Reader reader, int length)
     throws SQLException {
   checkOpen();
   try {
     _stmt.setCharacterStream(parameterIndex, reader, length);
   } catch (SQLException e) {
     handleException(e);
   }
 }
Example #5
0
  /**
   * Inserts a Clob with the specified length, using a stream source, then fetches it from the
   * database and checks the length.
   *
   * @param length number of characters in the Clob
   * @throws IOException if reading from the source fails
   * @throws SQLException if something goes wrong
   */
  private void insertAndFetchTest(long length) throws IOException, SQLException {
    PreparedStatement ps = prepareStatement("insert into BLOBCLOB(ID, CLOBDATA) values(?,?)");
    int id = BlobClobTestSetup.getID();
    ps.setInt(1, id);
    ps.setCharacterStream(2, new LoopingAlphabetReader(length), length);
    long tsStart = System.currentTimeMillis();
    ps.execute();
    println(
        "Inserted "
            + length
            + " chars (length specified) in "
            + (System.currentTimeMillis() - tsStart)
            + " ms");
    Statement stmt = createStatement();
    tsStart = System.currentTimeMillis();
    ResultSet rs = stmt.executeQuery("select CLOBDATA from BLOBCLOB where id = " + id);
    assertTrue("Clob not inserted", rs.next());
    Clob aClob = rs.getClob(1);
    assertEquals("Invalid length", length, aClob.length());
    println("Fetched length (" + length + ") in " + (System.currentTimeMillis() - tsStart) + " ms");
    rs.close();

    // Insert same Clob again, using the lengthless override.
    id = BlobClobTestSetup.getID();
    ps.setInt(1, id);
    ps.setCharacterStream(2, new LoopingAlphabetReader(length));
    tsStart = System.currentTimeMillis();
    ps.executeUpdate();
    println(
        "Inserted "
            + length
            + " chars (length unspecified) in "
            + (System.currentTimeMillis() - tsStart)
            + " ms");
    rs = stmt.executeQuery("select CLOBDATA from BLOBCLOB where id = " + id);
    assertTrue("Clob not inserted", rs.next());
    aClob = rs.getClob(1);
    assertEquals("Invalid length", length, aClob.length());
    println("Fetched length (" + length + ") in " + (System.currentTimeMillis() - tsStart) + " ms");
    rs.close();

    rollback();
  }
  public void setCharacterStream(int parameterIndex, Reader reader, int length)
      throws SQLException {
    Profiler profiler = _profilerPoint.start();

    try {
      _preparedStatement.setCharacterStream(parameterIndex, reader, length);
    } finally {
      profiler.finish();
    }
  }
 public void setCharacterStream(int idx, Reader reader, long length) throws SQLException {
   try {
     reader = markableReader(reader, length);
     addMementoEntry(
         "setCharacterStream", new Class[] {Reader.class, Long.TYPE}, idx, reader, length);
     wrapped.setCharacterStream(idx, reader, length);
     resetReader(reader);
   } catch (SQLException e) {
     throw new UcanaccessSQLException(e);
   }
 }
 public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
   String methodCall = "setCharacterStream(" + parameterIndex + ", " + reader + ")";
   argTraceSet(parameterIndex, "(Reader)", "<Reader>");
   try {
     realPreparedStatement.setCharacterStream(parameterIndex, reader);
   } catch (SQLException s) {
     reportException(methodCall, s);
     throw s;
   }
   reportReturn(methodCall);
 }
Example #9
0
 @Override
 public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
   long p = getPrecision();
   if (p > Integer.MAX_VALUE || p <= 0) {
     p = -1;
   }
   if (type == Value.BLOB) {
     prep.setBinaryStream(parameterIndex, getInputStream(), (int) p);
   } else {
     prep.setCharacterStream(parameterIndex, getReader(), (int) p);
   }
 }
Example #10
0
 /**
  * Obtains streams from the Clob reading portions of the content, always including the last
  * character in the Clob.
  *
  * <p>This case fills the Clob with Chinese/Japanese/Korean characters.
  */
 public void testGetCharacterStreamLongLastCharCJK() throws IOException, SQLException {
   CharAlphabet alphabet = CharAlphabet.cjkSubset();
   // Insert a Clob
   int length = 9001;
   PreparedStatement ps = prepareStatement("insert into BLOBCLOB(ID, CLOBDATA) values(?,?)");
   int id = BlobClobTestSetup.getID();
   ps.setInt(1, id);
   ps.setCharacterStream(2, new LoopingAlphabetReader(length, alphabet), length);
   ps.execute();
   ps.close();
   // Perform the actual test.
   getCharacterStreamLongLastChar(id, length, alphabet);
 }
 private void testLobTempFiles(Connection conn) throws SQLException {
   Statement stat = conn.createStatement();
   stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, DATA CLOB)");
   PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)");
   for (int i = 0; i < 5; i++) {
     prep.setInt(1, i);
     if (i % 2 == 0) {
       prep.setCharacterStream(2, new StringReader(getString(i)), -1);
     }
     prep.execute();
   }
   ResultSet rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");
   int check = 0;
   for (int i = 0; i < 5; i++) {
     assertTrue(rs.next());
     if (i % 2 == 0) {
       check = i;
     }
     assertEquals(getString(check), rs.getString(2));
   }
   assertFalse(rs.next());
   stat.execute("DELETE FROM TEST");
   for (int i = 0; i < 3; i++) {
     prep.setInt(1, i);
     prep.setCharacterStream(2, new StringReader(getString(i)), -1);
     prep.addBatch();
   }
   prep.executeBatch();
   rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");
   for (int i = 0; i < 3; i++) {
     assertTrue(rs.next());
     assertEquals(getString(i), rs.getString(2));
   }
   assertFalse(rs.next());
   stat.execute("DROP TABLE TEST");
 }
Example #12
0
 /**
  * Set given value on given PreparedStatement at given index with given SQL type.
  *
  * @param stmt The PreparedStatement to set value on.
  * @param index The index of the value in the PreparedStatement.
  * @param value The value to set.
  * @param sqlType The SQL type of the value.
  */
 public static void setValue(
     final PreparedStatement stmt, final int index, final Object value, final int sqlType) {
   try {
     if (value == null) {
       stmt.setNull(index, sqlType);
     } else {
       // Special processing for BLOB and CLOB types, because they are mapped
       // by Castor to java.io.InputStream and java.io.Reader, respectively,
       // while JDBC driver expects java.sql.Blob and java.sql.Clob.
       switch (sqlType) {
         case Types.FLOAT:
         case Types.DOUBLE:
           stmt.setDouble(index, ((Double) value).doubleValue());
           break;
         case Types.REAL:
           stmt.setFloat(index, ((Float) value).floatValue());
           break;
         case Types.TIME:
           stmt.setTime(index, (Time) value, getCalendar());
           break;
         case Types.DATE:
           stmt.setDate(index, (Date) value);
           break;
         case Types.TIMESTAMP:
           stmt.setTimestamp(index, (Timestamp) value, getCalendar());
           break;
         case Types.BLOB:
           try {
             InputStream stream = (InputStream) value;
             stmt.setBinaryStream(index, stream, stream.available());
           } catch (IOException ex) {
             throw new SQLException(ex.toString());
           }
           break;
         case Types.CLOB:
           Clob clob = (Clob) value;
           stmt.setCharacterStream(
               index, clob.getCharacterStream(), (int) Math.min(clob.length(), Integer.MAX_VALUE));
           break;
         default:
           stmt.setObject(index, value, sqlType);
           break;
       }
     }
   } catch (SQLException ex) {
     LOG.error("Unexpected SQL exception: ", ex);
   }
 }
 public void store(String cacheEntryName, InputStream inputStream, long expirationDate) {
   try {
     PreparedStatement stmt =
         connection.prepareStatement(
             "INSERT INTO " + tableName + " (id, expiration_date, response) VALUES(?, ?, ?)");
     stmt.setString(1, cacheEntryName);
     stmt.setTimestamp(2, new Timestamp(expirationDate));
     stmt.setCharacterStream(3, new InputStreamReader(inputStream, "UTF-8"), -1);
     stmt.execute();
     stmt.close();
   } catch (SQLException e) {
     e.printStackTrace();
     // ignore
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
     //			won't happen
   }
 }
 /**
  * According to the JDBC spec, BLOB and CLOB objects must stay open even if the result set is
  * closed (see ResultSet.close).
  */
 private void testLobStaysOpenUntilCommitted() throws Exception {
   Connection conn = getConnection();
   stat = conn.createStatement();
   stat.execute("create table test(id identity, c clob, b blob)");
   PreparedStatement prep = conn.prepareStatement("insert into test values(null, ?, ?)");
   prep.setString(1, "");
   prep.setBytes(2, new byte[0]);
   prep.execute();
   Random r = new Random(1);
   char[] chars = new char[100000];
   for (int i = 0; i < chars.length; i++) {
     chars[i] = (char) r.nextInt(10000);
   }
   String d = new String(chars);
   prep.setCharacterStream(1, new StringReader(d), -1);
   byte[] bytes = new byte[100000];
   r.nextBytes(bytes);
   prep.setBinaryStream(2, new ByteArrayInputStream(bytes), -1);
   prep.execute();
   conn.setAutoCommit(false);
   ResultSet rs = stat.executeQuery("select * from test order by id");
   rs.next();
   Clob c1 = rs.getClob(2);
   Blob b1 = rs.getBlob(3);
   rs.next();
   Clob c2 = rs.getClob(2);
   Blob b2 = rs.getBlob(3);
   assertFalse(rs.next());
   // now close
   rs.close();
   // but the LOBs must stay open
   assertEquals(0, c1.length());
   assertEquals(0, b1.length());
   assertEquals(chars.length, c2.length());
   assertEquals(bytes.length, b2.length());
   assertEquals("", c1.getSubString(1, 0));
   assertEquals(new byte[0], b1.getBytes(1, 0));
   assertEquals(d, c2.getSubString(1, (int) c2.length()));
   assertEquals(bytes, b2.getBytes(1, (int) b2.length()));
   stat.execute("drop table test");
   conn.close();
 }
  /** 保存带文本的数据 */
  @Test
  public void saveText() {
    Connection conn = null;
    PreparedStatement pstmt = null;

    conn = JDBCUtils.getConnection();
    String sql = "INSERT INTO bt_user (NAME,resume) VALUES(?,?)";
    try {
      pstmt = conn.prepareStatement(sql);
      pstmt.setString(1, "tom2");
      String path = "D:\\work\\Workspaces\\day14_jdbc\\src\\cn\\itcast\\mysql\\bt\\工作.txt";
      InputStream is = new FileInputStream(path);
      Reader reader = new InputStreamReader(is, "utf-8");
      pstmt.setCharacterStream(2, reader, is.available()); // 只有字节点才能得到流数据中的字节数
      pstmt.executeUpdate();
    } catch (SQLException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #16
0
  /**
   * Insert a row with a large clob into the test table. Read the row from the database and assign
   * the clob value to <code>clob</code>.
   *
   * @return The id of the row that was inserted
   * @throws java.sql.SQLException
   */
  private int initializeLongClob() throws SQLException {
    // Clob needs to be larger than one page for locking to occur
    final int lobLength = 40000;

    // Insert a long Clob
    PreparedStatement ps = prepareStatement("insert into BLOBCLOB(ID, CLOBDATA) values(?,?)");
    int id = BlobClobTestSetup.getID();
    ps.setInt(1, id);
    ps.setCharacterStream(2, new LoopingAlphabetReader(lobLength), lobLength);
    ps.execute();
    ps.close();
    commit();

    // Fetch the Clob object from the database
    Statement st = createStatement();
    ResultSet rs = st.executeQuery("select CLOBDATA from BLOBCLOB where ID=" + id);
    rs.next();
    clob = rs.getClob(1);
    rs.close();
    st.close();

    return id;
  }
Example #17
0
  static void create() throws SQLException, IOException {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
      conn = JdbcUtils.getConnection();
      String sql = "insert into clob_test(big_text)values(?)";
      ps = conn.prepareStatement(sql);

      File file = new File("src/cn/itcast/jdbc/JdbcUtils.java");
      Reader reader = new BufferedReader(new FileReader(file));

      ps.setCharacterStream(1, reader, (int) file.length()); // 字符流

      int i = ps.executeUpdate();

      reader.close();
      System.out.println("i=" + i);

    } finally {
      JdbcUtils.free(rs, ps, conn);
    }
  }
Example #18
0
  @Override
  public int insert(Object obj) {
    int result = 0;

    try {
      conn.setAutoCommit(false);

      if (bean.getParentId() == 0) {
        // 답글이 아닌 경우 그룹번호를 새롭게 구한다.
        stmt = conn.createStatement();
        rs = stmt.executeQuery("select max(GROUP_ID) from THEME_MESSAGE");
        int maxGroupId = 0;
        if (rs.next()) {
          maxGroupId = rs.getInt(1);
        }
        maxGroupId++;

        bean.setGroupId(maxGroupId);
        bean.setOrderNo(0);
      } else {
        // 특정 글의 답글인 경우,
        // 같은 그룹 번호 내에서의 출력 순서를 구한다.
        pstmt =
            conn.prepareStatement(
                "select max(ORDER_NO) from THEME_MESSAGE "
                    + "where PARENT_ID = ? or THEME_MESSAGE_ID = ?");
        pstmt.setInt(1, bean.getParentId());
        pstmt.setInt(2, bean.getParentId());
        rs = pstmt.executeQuery();
        int maxOrder = 0;
        if (rs.next()) {
          maxOrder = rs.getInt(1);
        }
        maxOrder++;
        bean.setOrderNo(maxOrder);
      }

      // 특정 글의 답변 글인 경우 같은 그룹 내에서
      // 순서 번호를 변경한다.
      if (bean.getOrderNo() > 0) {
        pstmt =
            conn.prepareStatement(
                "update THEME_MESSAGE set ORDER_NO = ORDER_NO + 1 "
                    + "where GROUP_ID = ? and ORDER_NO >= ?");
        pstmt.setInt(1, bean.getGroupId());
        pstmt.setInt(2, bean.getOrderNo());
        pstmt.executeUpdate();
      }
      // 새로운 글의 번호를 구한다.
      bean.setId(0);
      // 글을 삽입한다.
      pstmt = conn.prepareStatement("insert into bean_MESSAGE values (?,?,?,?,?,?,?,?,?,?,?)");
      pstmt.setInt(1, bean.getId());
      pstmt.setInt(2, bean.getGroupId());
      pstmt.setInt(3, bean.getOrderNo());
      pstmt.setInt(4, bean.getLevel());
      pstmt.setInt(5, bean.getParentId());
      //  pstmt.setTimestamp(6, bean.getRegister());
      pstmt.setString(7, bean.getName());
      pstmt.setString(8, bean.getEmail());
      pstmt.setString(9, bean.getImage());
      pstmt.setString(10, bean.getPassword());
      pstmt.setString(11, bean.getTitle());
      pstmt.executeUpdate();

      pstmt = conn.prepareStatement("insert into THEME_CONTENT values (?,?)");
      pstmt.setInt(1, bean.getId());
      pstmt.setCharacterStream(2, null);

      conn.commit();
    } catch (SQLException ex) {
      ex.printStackTrace();
    } finally {

    }
    return result;
  }
Example #19
0
  /**
   * Tests the exceptions thrown by the getCharacterStream (long pos, long length) for the following
   * conditions a) pos <= 0 b) pos > (length of LOB) c) length < 0 d) pos + length > (length of
   * LOB).
   *
   * @throws SQLException
   */
  public void testGetCharacterStreamLongExceptionConditions() throws SQLException {
    String str1 = "This is a test String. This is a test String";

    Reader r1 = new java.io.StringReader(str1);

    PreparedStatement ps = prepareStatement("insert into BLOBCLOB(ID, CLOBDATA) values(?,?)");
    int id = BlobClobTestSetup.getID();
    ps.setInt(1, id);
    ps.setCharacterStream(2, r1);
    ps.execute();
    ps.close();

    Statement st = createStatement();

    ResultSet rs = st.executeQuery("select CLOBDATA from " + "BLOBCLOB where ID=" + id);
    rs.next();
    Clob clob = rs.getClob(1);
    // check the case where pos <= 0
    try {
      // set pos as negative
      clob.getCharacterStream(-2L, 5L);
      // Should not come here. The exception has to be thrown.
      fail("FAIL: Expected SQLException for pos being negative " + "not thrown");
    } catch (SQLException sqle) {
      // The SQLState for the exception thrown when pos <= 0 is XJ070
      assertSQLState("XJ070", sqle);
    }

    // check for the case pos > length of clob
    try {
      // set the pos to any value greater than the Clob length
      clob.getCharacterStream(clob.length() + 1, 5L);
      // Should not come here. The exception has to be thrown.
      fail(
          "FAIL: Expected SQLException for position being greater than "
              + "length of LOB not thrown");
    } catch (SQLException sqle) {
      // The SQLState for the exception thrown when pos > length of Clob
      // is XJ076
      assertSQLState("XJ087", sqle);
    }

    // check for the case when length < 0
    try {
      // set length as negative
      clob.getCharacterStream(2L, -5L);
      // Should not come here. The exception has to be thrown.
      fail("Fail: expected exception for the length being negative " + "not thrown");
    } catch (SQLException sqle) {
      // The SQLState for the exception thrown when length < 0 of Clob
      // is XJ071
      assertSQLState("XJ071", sqle);
    }

    // check for the case when pos + length > length of Clob
    try {
      // set pos + length > length of Clob
      clob.getCharacterStream((clob.length() - 4), 10L);
      // Should not come here. The exception has to be thrown.
      fail(
          "Fail: expected exception for the sum of position and length"
              + " being greater than the LOB size not thrown");
    } catch (SQLException sqle) {
      // The SQLState for the exception thrown when length < 0 of Clob
      // is XJ087
      assertSQLState("XJ087", sqle);
    }
  }
  private void testClob(Connection conn) throws SQLException {
    trace("testClob");
    Statement stat = conn.createStatement();
    PreparedStatement prep;
    ResultSet rs;
    stat.execute("CREATE TABLE T_CLOB(ID INT PRIMARY KEY,V1 CLOB,V2 CLOB)");
    StringBuilder asciiBuffer = new StringBuilder();
    int len = getLength();
    for (int i = 0; i < len; i++) {
      asciiBuffer.append((char) ('a' + (i % 20)));
    }
    String ascii1 = asciiBuffer.toString();
    String ascii2 = "Number2 " + ascii1;
    prep = conn.prepareStatement("INSERT INTO T_CLOB VALUES(?,?,?)");

    prep.setInt(1, 1);
    prep.setString(2, null);
    prep.setNull(3, Types.CLOB);
    prep.executeUpdate();

    prep.clearParameters();
    prep.setInt(1, 2);
    prep.setAsciiStream(2, null, 0);
    prep.setCharacterStream(3, null, 0);
    prep.executeUpdate();

    prep.clearParameters();
    prep.setInt(1, 3);
    prep.setCharacterStream(2, new StringReader(ascii1), ascii1.length());
    prep.setCharacterStream(3, null, 0);
    prep.setAsciiStream(3, new ByteArrayInputStream(ascii2.getBytes()), ascii2.length());
    prep.executeUpdate();

    prep.clearParameters();
    prep.setInt(1, 4);
    prep.setNull(2, Types.CLOB);
    prep.setString(2, ascii2);
    prep.setCharacterStream(3, null, 0);
    prep.setNull(3, Types.CLOB);
    prep.setString(3, ascii1);
    prep.executeUpdate();

    prep.clearParameters();
    prep.setInt(1, 5);
    prep.setObject(2, new StringReader(ascii1));
    prep.setObject(3, new StringReader(ascii2), Types.CLOB, 0);
    prep.executeUpdate();

    rs = stat.executeQuery("SELECT ID, V1, V2 FROM T_CLOB ORDER BY ID");

    rs.next();
    assertEquals(1, rs.getInt(1));
    assertTrue(rs.getCharacterStream(2) == null && rs.wasNull());
    assertTrue(rs.getAsciiStream(3) == null && rs.wasNull());

    rs.next();
    assertEquals(2, rs.getInt(1));
    assertTrue(rs.getString(2) == null && rs.wasNull());
    assertTrue(rs.getString(3) == null && rs.wasNull());

    rs.next();
    assertEquals(3, rs.getInt(1));
    assertEquals(ascii1, rs.getString(2));
    assertEquals(ascii2, rs.getString(3));

    rs.next();
    assertEquals(4, rs.getInt(1));
    assertEquals(ascii2, rs.getString(2));
    assertEquals(ascii1, rs.getString(3));

    rs.next();
    assertEquals(5, rs.getInt(1));
    assertEquals(ascii1, rs.getString(2));
    assertEquals(ascii2, rs.getString(3));

    assertFalse(rs.next());
    assertTrue(prep.getWarnings() == null);
    prep.clearWarnings();
    assertTrue(prep.getWarnings() == null);
    assertTrue(conn == prep.getConnection());
  }
Example #21
0
  /**
   * Takes a vector full of property lists and generates a report.
   *
   * @param args Command line arguments. args[0] should be the config filename.
   */
  public static void main(String[] args) {
    // Load the database properties from properties file
    Properties properties = new Properties();

    // Load config file
    String configFile = null;
    if (args.length > 0) configFile = args[0];

    try {
      if (configFile == null) {
        System.out.println("Database config file not set.");
        return;
      } else properties.load(new FileInputStream(configFile));
    } catch (IOException e) {
      System.out.println("Error opening config file.");
    }

    String url = properties.getProperty("databaseUrl");
    String username = properties.getProperty("username");
    String password = properties.getProperty("password");
    String dir = System.getProperty("user.dir"); // Current working directory
    Connection con = null;

    // Try to open file containing javac output
    String output = "";
    try {
      BufferedReader outputReader = new BufferedReader(new FileReader(dir + "/CompileOut.txt"));

      while (outputReader.ready()) output += outputReader.readLine() + '\n';

      // Close file
      outputReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("Error opening compilation output file.");
      return;
    } catch (IOException e) {
      System.out.println("I/O Exception Occured.");
      return;
    }

    boolean hasDriver = false;
    // Create class for the driver
    try {
      Class.forName("com.mysql.jdbc.Driver");
      hasDriver = true;
    } catch (Exception e) {
      System.out.println("Failed to load MySQL JDBC driver class.");
    }

    // Create connection to database if the driver was found
    if (hasDriver) {
      try {
        con = DriverManager.getConnection(url, username, password);
      } catch (SQLException e) {
        System.out.println("Couldn't get connection!");
      }
    }

    // Check that a connection was made
    if (con != null) {
      long userEventId = -1;

      // Store results from the report into the database
      try {
        BufferedReader rd =
            new BufferedReader(
                new FileReader(dir + "/userId.txt")); // Read userId.txt to get userId
        String userId = rd.readLine(); // Store userId from text file
        rd.close();

        // Insert the report into the table and get the auto_increment id for it
        Statement stmt = con.createStatement();
        stmt.executeUpdate("INSERT INTO userEvents (userId) VALUES ('" + userId + "')");
        ResultSet result = stmt.getGeneratedKeys();
        result.next();
        userEventId = result.getLong(1);

        // Close the statement
        stmt.close();

        // Prepare statement for adding the compilation error to the userEvent
        PreparedStatement compErrorPrepStmt =
            con.prepareStatement(
                "INSERT INTO userEventCompilationErrors(userEventId, output) VALUES (?, ?)");

        // Insert userEventId and docletId into the database
        compErrorPrepStmt.setLong(1, userEventId);
        compErrorPrepStmt.setString(2, output);
        compErrorPrepStmt.executeUpdate();

        // Close the prepare statements
        compErrorPrepStmt.close();
      } catch (Exception e) {
        System.out.println("Exception Occurred");
        System.out.println(e);
      }

      // Store the java files for the report
      try {
        // Prepare statement for storing files
        PreparedStatement filePrepStmt =
            con.prepareStatement(
                "INSERT INTO files(userEventId, filename, contents) VALUES ("
                    + userEventId
                    + ", ?, ?)");

        // Get the list of files from source.txt
        BufferedReader rd =
            new BufferedReader(
                new FileReader(dir + "/source.txt")); // Read userId.txt to get userId
        while (rd.ready()) {
          String filename = rd.readLine(); // Store userId from text file
          // Remove the "src/" from the beginning to get the real file name
          String realname = filename.substring(4);
          filePrepStmt.setString(1, realname);

          // Read in the contents of the files
          String contents = "";
          File javaFile = new File(dir + "/" + filename);
          int length = (int) javaFile.length();

          // Add parameter for file contents to the prepared statement and execute it
          filePrepStmt.setCharacterStream(2, new BufferedReader(new FileReader(javaFile)), length);
          filePrepStmt.executeUpdate();
        }
        rd.close();
      } catch (IOException e) {
        System.err.println("I/O Exception Occured.");
      } catch (SQLException e) {
        System.err.println("SQL Exception Occured.");
      }
    }
  }
 public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
   delegate.setCharacterStream(parameterIndex, reader);
 }
 @Override
 public void setCharacterStream(int parameterIndex, Reader x) throws SQLException {
   stmt.setCharacterStream(parameterIndex, x);
   logValue(parameterIndex, x == null ? null : "<CharacterStream>");
 }
 public void setCharacterStream(int parameterIndex, Reader reader, int length)
     throws SQLException {
   saveParam(parameterIndex, "" + reader, "Boolean");
   statement.setCharacterStream(parameterIndex, reader, length);
 }
 @Override
 public void setClob(int parameterIndex, Reader x, long length) throws SQLException {
   stmt.setCharacterStream(parameterIndex, x, length);
   logValue(parameterIndex, x == null ? null : "<Clob>");
 }
  /**
   * sets the value of a bytes field in the specified column. <br>
   * <br>
   *
   * @param pstmt prepared statement
   * @param var value to bind to the last parameter in the sql statement.
   * @param pos number of column of bytes field.
   */
  public PreparedStatement setBytes(PreparedStatement pstmt, String var, int pos)
      throws SQLException {
    pstmt.setCharacterStream(pos, new StringReader(var), var.length());

    return pstmt;
  }
 public void set(PreparedStatement st, Object value, int index) throws SQLException {
   char[] chars = toInternalFormat(value);
   st.setCharacterStream(index, new CharArrayReader(chars), chars.length);
 }
  private void testClob(int length) throws Exception {
    Random r = new Random(length);
    char[] data = new char[length];

    // Unicode problem:
    // The UCS code values 0xd800-0xdfff (UTF-16 surrogates)
    // as well as 0xfffe and 0xffff (UCS non-characters)
    // should not appear in conforming UTF-8 streams.
    // (String.getBytes("UTF-8") only returns 1 byte for 0xd800-0xdfff)
    for (int i = 0; i < length; i++) {
      char c;
      do {
        c = (char) r.nextInt();
      } while (c >= 0xd800 && c <= 0xdfff);
      data[i] = c;
    }
    Clob c = conn.createClob();
    Writer out = c.setCharacterStream(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.setClob(2, c);
    prep.execute();

    c = conn.createClob();
    c.setString(1, new String(data));
    prep.setInt(1, 2);
    prep.setClob(2, c);
    prep.execute();

    prep.setInt(1, 3);
    prep.setCharacterStream(2, new StringReader(new String(data)));
    prep.execute();

    prep.setInt(1, 4);
    prep.setCharacterStream(2, new StringReader(new String(data)), -1);
    prep.execute();

    NClob nc;
    nc = conn.createNClob();
    nc.setString(1, new String(data));
    prep.setInt(1, 5);
    prep.setNClob(2, nc);
    prep.execute();

    prep.setInt(1, 5);
    prep.setNClob(2, new StringReader(new String(data)));
    prep.execute();

    prep.setInt(1, 6);
    prep.setNClob(2, new StringReader(new String(data)), -1);
    prep.execute();

    prep.setInt(1, 7);
    prep.setNString(2, new String(data));
    prep.execute();

    ResultSet rs;
    rs = stat.executeQuery("select * from test");
    rs.next();
    Clob c2 = rs.getClob(2);
    assertEquals(length, c2.length());
    String s = c.getSubString(1, length);
    String s2 = c2.getSubString(1, length);
    while (rs.next()) {
      c2 = rs.getClob(2);
      assertEquals(length, c2.length());
      s2 = c2.getSubString(1, length);
      assertEquals(s, s2);
    }
  }
Example #29
0
 public void setData(PreparedStatement preparedStmt, int columnIndex, Object obj)
     throws SQLException {
   String dataString = (String) obj;
   preparedStmt.setCharacterStream(columnIndex, new StringReader(dataString), dataString.length());
 }
 protected void insertObjectDo(Object value, PreparedStatement statement, int index)
     throws SQLException {
   statement.setCharacterStream(
       index, ((CharacterStream) value).getReader(), ((CharacterStream) value).getLength());
 }