Java Code Examples for java.sql.ResultSet.close()

The following are Jave code examples for showing how to use close() of the java.sql.ResultSet class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ProyectoPacientes   File: MetaDataRegressionTest.java   View Source Code Vote up 6 votes
/**
 * Tests bug reported by OpenOffice team with getColumns and LONGBLOB
 * 
 * @throws Exception
 *             if any errors occur
 */
public void testGetColumns() throws Exception {
    try {
        this.stmt.execute("CREATE TABLE IF NOT EXISTS longblob_regress(field_1 longblob)");

        DatabaseMetaData dbmd = this.conn.getMetaData();
        ResultSet dbmdRs = null;

        try {
            dbmdRs = dbmd.getColumns("", "", "longblob_regress", "%");

            while (dbmdRs.next()) {
                dbmdRs.getInt(7);
            }
        } finally {
            if (dbmdRs != null) {
                try {
                    dbmdRs.close();
                } catch (SQLException ex) {
                }
            }
        }
    } finally {
        this.stmt.execute("DROP TABLE IF EXISTS longblob_regress");
    }
}
 
Example 2
Project: calcite-avatica   File: JdbcResultSet.java   View Source Code Vote up 6 votes
public static JdbcResultSet create(String connectionId, int statementId,
    ResultSet resultSet, int maxRowCount, Meta.Signature signature) {
  try {
    final Calendar calendar = DateTimeUtils.calendar();
    final int fetchRowCount;
    if (maxRowCount == JdbcMeta.UNLIMITED_COUNT) {
      fetchRowCount = -1;
    } else if (maxRowCount < 0L) {
      fetchRowCount = AvaticaStatement.DEFAULT_FETCH_SIZE;
    } else if (maxRowCount > AvaticaStatement.DEFAULT_FETCH_SIZE) {
      fetchRowCount = AvaticaStatement.DEFAULT_FETCH_SIZE;
    } else {
      fetchRowCount = maxRowCount;
    }
    final Meta.Frame firstFrame = frame(null, resultSet, 0, fetchRowCount, calendar,
        Optional.of(signature));
    if (firstFrame.done) {
      resultSet.close();
    }
    return new JdbcResultSet(connectionId, statementId, true, signature,
        firstFrame);
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
}
 
Example 3
Project: mm-system-2017   File: DataAccess.java   View Source Code Vote up 6 votes
@Override
public Mentor getMentorOfMentee(int menteeId) throws SQLException {
	Mentor m = null;
	PreparedStatement stm = c.prepareStatement(SQLStatements.selectPairsByMenteeIdAndActiveStats);
	stm.setInt(1, menteeId);
	stm.setInt(2, 1);
	ResultSet rs = stm.executeQuery();
	if (rs.next()) {
		m = (Mentor) getUser(rs.getInt(2));
	}
	rs.close();
	stm.close();

	return m;

}
 
Example 4
Project: lams   File: JDBC4ClientInfoProviderSP.java   View Source Code Vote up 6 votes
public synchronized Properties getClientInfo(java.sql.Connection conn) throws SQLException {
    ResultSet rs = null;

    Properties props = new Properties();

    try {
        this.getClientInfoBulkSp.execute();

        rs = this.getClientInfoBulkSp.getResultSet();

        while (rs.next()) {
            props.setProperty(rs.getString(1), rs.getString(2));
        }
    } finally {
        if (rs != null) {
            rs.close();
        }
    }

    return props;
}
 
Example 5
Project: lams   File: DatabaseMetadata.java   View Source Code Vote up 6 votes
private void initSequences(Connection connection, Dialect dialect) throws SQLException {
	if ( dialect.supportsSequences() ) {
		String sql = dialect.getQuerySequencesString();
		if (sql!=null) {

			Statement statement = null;
			ResultSet rs = null;
			try {
				statement = connection.createStatement();
				rs = statement.executeQuery(sql);

				while ( rs.next() ) {
					sequences.add( StringHelper.toLowerCase(rs.getString(1)).trim() );
				}
			}
			finally {
				if ( rs != null ) {
					rs.close();
				}
				if ( statement != null ) {
					statement.close();
				}
			}
		}
	}
}
 
Example 6
Project: BibliotecaPS   File: ConnectionTest.java   View Source Code Vote up 5 votes
/**
 * IPv6 Connection test.
 * 
 * @throws SQLException
 */
public void testIPv6() throws Exception {

    if (!versionMeetsMinimum(5, 6)) {
        return;
        // this test could work with MySQL 5.5 but requires specific server configuration, e.g. "--bind-address=::"
    }

    Properties connProps = getPropertiesFromTestsuiteUrl();

    String host = "::1"; // IPv6 loopback
    int port = Integer.parseInt(connProps.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY));
    String username = connProps.getProperty(NonRegisteringDriver.USER_PROPERTY_KEY);

    String ipv6Url = String.format("jdbc:mysql://address=(protocol=tcp)(host=%s)(port=%d)", host, port);

    Connection testConn = null;
    Statement testStmt = null;
    ResultSet testRS = null;

    connProps = getHostFreePropertiesFromTestsuiteUrl();

    testConn = DriverManager.getConnection(ipv6Url, connProps);
    testStmt = testConn.createStatement();
    testRS = testStmt.executeQuery("SELECT USER()");

    assertTrue(testRS.next());
    assertTrue(testRS.getString(1).startsWith(username));

    testRS.close();
    testStmt.close();
    testConn.close();
}
 
Example 7
Project: parabuild-ci   File: ZaurusTableForm.java   View Source Code Vote up 5 votes
private void fetchPrimaryKeys() {

        Vector temp = new Vector(20);

        try {
            if (cConn == null) {
                return;
            }

            if (dbmeta == null) {
                dbmeta = cConn.getMetaData();
            }

            ResultSet colList = dbmeta.getPrimaryKeys(null, null, tableName);

            while (colList.next()) {
                temp.addElement(colList.getString("COLUMN_NAME"));
            }

            colList.close();
        } catch (SQLException e) {
            ZaurusEditor.printStatus("SQL Exception: " + e.getMessage());
        }

        primaryKeys = new String[temp.size()];

        temp.copyInto(primaryKeys);

        pkColIndex = new int[primaryKeys.length];

        for (int i = 0; i < primaryKeys.length; i++) {
            pkColIndex[i] = this.getColIndex(primaryKeys[i]);
        }    // end of for (int i=0; i<primaryKeys.length; i++)
    }
 
Example 8
Project: Lucid2.0   File: MapleGuildAlliance.java   View Source Code Vote up 5 votes
public static final int createToDb(final int leaderId, final String name, final int guild1, final int guild2) {
    int ret = -1;
    if (name.length() > 12) {
        return ret;
    }
    Connection con = DatabaseConnection.getConnection();
    try {
        PreparedStatement ps = con.prepareStatement("SELECT id FROM alliances WHERE name = ?");
        ps.setString(1, name);
        ResultSet rs = ps.executeQuery();

        if (rs.first()) {// name taken
            rs.close();
            ps.close();
            return ret;
        }
        ps.close();
        rs.close();

        ps = con.prepareStatement("insert into alliances (name, guild1, guild2, leaderid) VALUES (?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, name);
        ps.setInt(2, guild1);
        ps.setInt(3, guild2);
        ps.setInt(4, leaderId);
        ps.execute();
        rs = ps.getGeneratedKeys();
        if (rs.next()) {
            ret = rs.getInt(1);
        }
        rs.close();
        ps.close();
    } catch (SQLException SE) {
        System.err.println("SQL THROW");
    }
    return ret;
}
 
Example 9
Project: Lucid2.0   File: CashShop.java   View Source Code Vote up 5 votes
public List<Pair<Item, String>> loadGifts() {
    List<Pair<Item, String>> gifts = new ArrayList<>();
    Connection con = DatabaseConnection.getConnection();
    try {
        PreparedStatement ps = con.prepareStatement("SELECT * FROM `gifts` WHERE `recipient` = ?");
        ps.setInt(1, characterId);
        ResultSet rs = ps.executeQuery();

        while (rs.next()) {
            CashItemInfo cItem = CashItemFactory.getInstance().getItem(rs.getInt("sn"));
            if (cItem == null) {
                continue;
            }
            Item item = toItem(cItem, rs.getInt("uniqueid"), rs.getString("from"));
            gifts.add(new Pair<>(item, rs.getString("message")));
            uniqueids.add(item.getUniqueId());
            List<Integer> packages = CashItemFactory.getInstance().getPackageItems(cItem.getId());
            if (packages != null && packages.size() > 0) {
                for (int packageItem : packages) {
                    CashItemInfo pack = CashItemFactory.getInstance().getSimpleItem(packageItem);
                    if (pack != null) {
                        addToInventory(toItem(pack, rs.getString("from")));
                    }
                }
            } else {
                addToInventory(item);
            }
        }

        rs.close();
        ps.close();
        ps = con.prepareStatement("DELETE FROM `gifts` WHERE `recipient` = ?");
        ps.setInt(1, characterId);
        ps.executeUpdate();
        ps.close();
        save();
    } catch (SQLException sqle) {
    }
    return gifts;
}
 
Example 10
Project: EatDubbo   File: DatabaseStatusChecker.java   View Source Code Vote up 5 votes
public Status check() {
    boolean ok;
    try {
        Connection connection = dataSource.getConnection();
        try {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet resultSet = metaData.getTypeInfo();
            try {
                ok = resultSet.next();
            } finally {
                resultSet.close();
            }
            if (message == null) {
                message = metaData.getURL()
                    + " (" + metaData.getDatabaseProductName() 
                    + " " + metaData.getDatabaseProductVersion()
                    + ", " + getIsolation(metaData.getDefaultTransactionIsolation()) + ")";
            }
            if (version == 0) {
                version = metaData.getDatabaseMajorVersion();
            }
        } finally {
            connection.close();
        }
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
        ok = false;
    }
    return new Status(! ok ? Status.Level.ERROR : (version < 5 ? Status.Level.WARN : Status.Level.OK), message);
}
 
Example 11
Project: AeroStory   File: MapleGuild.java   View Source Code Vote up 5 votes
public static void displayGuildRanks(MapleClient c, int npcid) {
    try {
        ResultSet rs;
        try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("SELECT `name`, `GP`, `logoBG`, `logoBGColor`, " + "`logo`, `logoColor` FROM guilds ORDER BY `GP` DESC LIMIT 50")) {
            rs = ps.executeQuery();
            c.announce(MaplePacketCreator.showGuildRanks(npcid, rs));
        }
        rs.close();
    } catch (SQLException e) {
        System.out.println("failed to display guild ranks. " + e);
    }
}
 
Example 12
Project: AeroStory   File: BBSOperationHandler.java   View Source Code Vote up 5 votes
public static void deleteBBSReply(MapleClient client, int replyid) {
    MapleCharacter mc = client.getPlayer();
    if (mc.getGuildId() <= 0) {
        return;
    }
    int threadid;
    Connection con = DatabaseConnection.getConnection();
    try {
        PreparedStatement ps = con.prepareStatement("SELECT postercid, threadid FROM bbs_replies WHERE replyid = ?");
        ps.setInt(1, replyid);
        ResultSet rs = ps.executeQuery();
        if (!rs.next()) {
            rs.close();
            ps.close();
            return;
        }
        if (mc.getId() != rs.getInt("postercid") && mc.getGuildRank() > 2) {
            rs.close();
            ps.close();
            return;
        }
        threadid = rs.getInt("threadid");
        rs.close();
        ps.close();
        ps = con.prepareStatement("DELETE FROM bbs_replies WHERE replyid = ?");
        ps.setInt(1, replyid);
        ps.execute();
        ps.close();
        ps = con.prepareStatement("UPDATE bbs_threads SET replycount = replycount - 1 WHERE threadid = ?");
        ps.setInt(1, threadid);
        ps.execute();
        ps.close();
        displayThread(client, threadid, false);
    } catch (SQLException se) {
        se.printStackTrace();
    }
}
 
Example 13
Project: parabuild-ci   File: AbstractEntityPersister.java   View Source Code Vote up 5 votes
/**
 * Retrieve the version number
 */
public Object getCurrentVersion(Serializable id, SessionImplementor session) throws HibernateException {
	
	if ( log.isTraceEnabled() ) {
		log.trace( "Getting version: " +  MessageHelper.infoString(this, id) );
	}
	
	try {
		
		PreparedStatement st = session.getBatcher().prepareStatement( getVersionSelectString() );
		try {
			getIdentifierType().nullSafeSet(st, id, 1, session);
			
			ResultSet rs = st.executeQuery();
			try {
				if ( !rs.next() ) return null;
				if ( !isVersioned() ) return this;
				return getVersionType().nullSafeGet(rs, getVersionColumnName(), session, null);
			}
			finally {
				rs.close();
			}
		}
		finally {
			session.getBatcher().closeStatement(st);
		}
		
	}
	catch (SQLException sqle) {
		throw convert( sqle, "could not retrieve version: " + MessageHelper.infoString(this, id) );
	}
	
}
 
Example 14
Project: HTAPBench   File: MysqlGetStats.java   View Source Code Vote up 5 votes
public long getStats(String t) throws SQLException {
	ResultSet res = stmt
			.executeQuery("SHOW GLOBAL STATUS WHERE Variable_name=\"" + t
					+ "\" ");
	res.next();
	long value = res.getLong(2);
	res.close();
	return value;
}
 
Example 15
Project: mapr-music   File: ReportingDao.java   View Source Code Vote up 5 votes
/**
 * Execute the SQL statement and return a list of K/V
 *
 * @param sql query.
 * @return
 */
private List<Pair> populatePaiFromSQL(String sql) {

    Stopwatch stopwatch = Stopwatch.createStarted();
    List<Pair> pairs = new ArrayList<>();
    try {

        log.debug("Executing SQL :\n\t" + sql);

        Statement st = getConnection().createStatement();
        ResultSet rs = st.executeQuery(sql);
        while (rs.next()) {
            String label = rs.getString(1);
            if (label == null || label.trim().isEmpty()) {
                label = "Unknown";
            }
            pairs.add(new Pair(label, rs.getString(2)));
        }
        rs.close();
        st.close();
        connection.close();

    } catch (Exception e) {
        e.printStackTrace();
        // TODO: Manage exception
    }

    log.debug("Performing query: '{}' took: {}", sql, stopwatch);
    return pairs;
}
 
Example 16
Project: dubbocloud   File: DatabaseStatusChecker.java   View Source Code Vote up 5 votes
public Status check() {
    boolean ok;
    try {
        Connection connection = dataSource.getConnection();
        try {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet resultSet = metaData.getTypeInfo();
            try {
                ok = resultSet.next();
            } finally {
                resultSet.close();
            }
            if (message == null) {
                message = metaData.getURL()
                    + " (" + metaData.getDatabaseProductName() 
                    + " " + metaData.getDatabaseProductVersion()
                    + ", " + getIsolation(metaData.getDefaultTransactionIsolation()) + ")";
            }
            if (version == 0) {
                version = metaData.getDatabaseMajorVersion();
            }
        } finally {
            connection.close();
        }
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
        ok = false;
    }
    return new Status(! ok ? Status.Level.ERROR : (version < 5 ? Status.Level.WARN : Status.Level.OK), message);
}
 
Example 17
Project: L2jBrasil   File: L2Clan.java   View Source Code Vote up 5 votes
/**
 * @return Returns the noticeEnabled.
 */
public boolean isNoticeEnabled()
{
 String result="";
 Connection con = null;
 try
 {
    
	 con = L2DatabaseFactory.getInstance().getConnection();
	 PreparedStatement statement = con.prepareStatement("SELECT enabled FROM clan_notices WHERE clanID=?");
	 statement.setInt(1, getClanId());
	 ResultSet rset = statement.executeQuery();
    
	 while (rset.next())
	 {
		 result = rset.getString("enabled");
	 }
    
	 rset.close();
	 statement.close();
	 con.close();
    
 } catch (Exception e)
 {
	 if (Config.DEBUG)
	 System.out.println("BBS: Error while reading _noticeEnabled for clan "+ this.getClanId() + "");
	 if(e.getMessage()!=null)
		 if (Config.DEBUG) 
		 System.out.println("BBS: Exception = "+e.getMessage()+"");
 }
 if (result.isEmpty())
 {
	 insertNotice();
	 return false;
 }
 else if(result.compareToIgnoreCase("true")==0)
	 return true;
 else
	 return false;
}
 
Example 18
Project: parabuild-ci   File: ZaurusTableForm.java   View Source Code Vote up 5 votes
private void fetchColumns() {

        Vector temp     = new Vector(20);
        Vector tempType = new Vector(20);

        try {
            if (cConn == null) {
                return;
            }

            if (dbmeta == null) {
                dbmeta = cConn.getMetaData();
            }

            ResultSet colList = dbmeta.getColumns(null, null, tableName, "%");

            while (colList.next()) {
                temp.addElement(colList.getString("COLUMN_NAME"));
                tempType.addElement(new Short(colList.getShort("DATA_TYPE")));
            }

            colList.close();
        } catch (SQLException e) {
            ZaurusEditor.printStatus("SQL Exception: " + e.getMessage());
        }

        columns = new String[temp.size()];

        temp.copyInto(columns);

        columnTypes = new short[temp.size()];

        for (int i = 0; i < columnTypes.length; i++) {
            columnTypes[i] = ((Short) tempType.elementAt(i)).shortValue();
        }
    }
 
Example 19
Project: aliyun-maxcompute-data-collectors   File: OracleManager.java   View Source Code Vote up 4 votes
@Override
public Map<String, String>
  getColumnTypeNamesForProcedure(String procedureName) {
  Map<String, String> ret = new TreeMap<String, String>();
  try {
    DatabaseMetaData metaData = this.getConnection().getMetaData();
    ResultSet results = metaData.getProcedureColumns(null, null,
      procedureName, null);
    if (null == results) {
      return null;
    }

    try {
      while (results.next()) {
        if (results.getInt("COLUMN_TYPE")
        != DatabaseMetaData.procedureColumnReturn) {
          int index = results.getInt("ORDINAL_POSITION");
          if (index < 0) {
            continue; // actually the return type
          }
          // we don't care if we get several rows for the
          // same ORDINAL_POSITION (e.g. like H2 gives us)
          // as we'll just overwrite the entry in the map:
          ret.put(
            results.getString("COLUMN_NAME"),
            results.getString("TYPE_NAME"));
        }
      }
      LOG.debug("Columns returned = " + StringUtils.join(ret.keySet(), ","));
      LOG.debug(
        "Type names returned = " + StringUtils.join(ret.values(), ","));
      return ret.isEmpty() ? null : ret;
    } finally {
      results.close();
      getConnection().commit();
    }
  } catch (SQLException sqlException) {
    LoggingUtils.logAll(LOG, "Error reading primary key metadata: "
      + sqlException.toString(), sqlException);
    return null;
  }
}
 
Example 20
Project: mm-system-2017   File: DataAccess.java   View Source Code Vote up 4 votes
@Override
public Pair addPair1(int mentorId, int menteeId) throws SQLException {
	Pair p = null;
	PreparedStatement stm = c.prepareStatement(SQLStatements.selectMentorById);
	stm.setInt(1, mentorId);
	ResultSet rs = stm.executeQuery();
	if (!rs.next()) { // user does not exist
		rs.close();
		stm.close();

		throw new SQLException("user-mentor does not exist");
	}
	stm = c.prepareStatement(SQLStatements.selectMenteeById);
	stm.setInt(1, menteeId);
	rs = stm.executeQuery();
	if (!rs.next()) { // user does not exist
		rs.close();
		stm.close();

		throw new SQLException("user-mentee does not exist");
	}
	stm = c.prepareStatement(SQLStatements.insertPair, Statement.RETURN_GENERATED_KEYS);
	// checking witch user is the mentor and witch is the mentee
	stm.setInt(1, mentorId);
	stm.setInt(2, menteeId);
	stm.setInt(3, 1);
	stm.setDate(4, Date.valueOf(LocalDate.now()));
	int num = stm.executeUpdate();
	if (num == 0) {
		rs.close();
		stm.close();

		throw new SQLException("Creating pair failed, no rows affected.");

	}

	try (ResultSet generatedKeys = stm.getGeneratedKeys()) {
		if (generatedKeys.next()) {
			p = getPair(generatedKeys.getInt(1));
		} else {
			rs.close();
			stm.close();

			throw new SQLException("Creating user failed, no ID obtained.");

		}
	}
	rs.close();
	stm.close();

	return p;

}