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

The following are Jave code examples for showing how to use getRow() 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: GUI-Sorting-Time-Comparison-using-JavaFx   File: MainController.java   View Source Code Vote up 6 votes
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
	try {
		myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/gui_assignment?autoReconnect=true&useSSL=false", "root", "root");
		stmt = myConn.createStatement();
		
		ResultSet rs = stmt.executeQuery("select Temperature_Reading from temp_values");
		values = new int[rs.last() ? rs.getRow() : 0];
		
		int[] temp = {10000,100000,500000};
		noOfTempReadings = temp;
		
		rs.setFetchDirection(ResultSet.FETCH_REVERSE);
		rs.next();
		int i = values.length-1;
		while (rs.previous()) {
			values[i--] = rs.getInt("Temperature_Reading");
		}
	} catch (SQLException e) {
		e.printStackTrace();
		System.err.println("DATABASE CONNECT ERROR");
		System.exit(1);
	}
	
	System.out.println("No. of entries in database = "+values.length);
	
	ObservableList<String> pivotValues = FXCollections.observableArrayList("n/2","n/4","n/6");
	pivotSelect.setItems(pivotValues);
	pivotSelect.setValue("n/2");
	pivotSelect.setDisable(true);
	
	ObservableList<Integer> baseValues = FXCollections.observableArrayList(2,10,16);
	base.setItems(baseValues);
	base.setValue(10);
	base.setDisable(true);
	
	btnViewGraph.setDisable(true);
}
 
Example 2
Project: OpenDiabetes   File: TestViewAsterisks.java   View Source Code Vote up 6 votes
/**
 *  ensures the content of a given table matches a given object array's content
 */
private void ensureTableContent(String tableName,
                                Object[][] tableData) throws SQLException {

    ResultSet lhs = m_statement.executeQuery("SELECT * FROM \""
        + tableName + "\"");
    ResultSetMetaData meta     = lhs.getMetaData();
    int               colCount = meta.getColumnCount();

    while (lhs.next()) {
        int row = lhs.getRow();

        assertEquals(colCount, tableData[row - 1].length);

        for (int col = 1; col <= colCount; ++col) {
            assertEquals(
                "unexpected table content in " + tableName + " (row "
                + row + ", col " + col + ")", tableData[row - 1][col - 1],
                                              lhs.getObject(col));
        }
    }
}
 
Example 3
Project: sjk   File: AppRankDaoImpl.java   View Source Code Vote up 6 votes
@Override
public List<App> getAppDefultRank(final int typeId, final int top) {
    PreparedStatementCallback<List<App>> cb = new PreparedStatementCallback<List<App>>() {
        @Override
        public List<App> doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.setInt(1, typeId);
            ps.setInt(2, top);
            ResultSet rs = null;
            try {
                rs = ps.executeQuery();
                if (rs.last()) {
                    int count = rs.getRow();
                    List<App> list = new ArrayList<App>(count);
                    rs.beforeFirst();
                    App app = null;
                    while (rs.next()) {
                        app = appRowMapper.mapRow(rs, rs.getRow());
                        changeOutputImpl.setUrls(app);
                        list.add(app);
                    }
                    return list;
                }

            } catch (Exception e) {
                logger.error("SQL data error:", e);
                return null;
            } finally {
                if (null != rs)
                    rs.close();
            }
            return null;
        }
    };
    return jdbcTemplate.execute(QUERY_APP_DEFAULT_TOP_SQL, cb);
}
 
Example 4
Project: parabuild-ci   File: TestViewAsterisks.java   View Source Code Vote up 6 votes
/**
 *  ensures the content of a given table matches a given object array's content
 */
private void ensureTableContent(String tableName,
                                Object[][] tableData) throws SQLException {

    ResultSet lhs = m_statement.executeQuery("SELECT * FROM \""
        + tableName + "\"");
    ResultSetMetaData meta     = lhs.getMetaData();
    int               colCount = meta.getColumnCount();

    while (lhs.next()) {
        int row = lhs.getRow();

        assertEquals(colCount, tableData[row - 1].length);

        for (int col = 1; col <= colCount; ++col) {
            assertEquals(
                "unexpected table content in " + tableName + " (row "
                + row + ", col " + col + ")", tableData[row - 1][col - 1],
                                              lhs.getObject(col));
        }
    }
}
 
Example 5
Project: uroborosql   File: AuditLogSqlFilter.java   View Source Code Vote up 6 votes
@Override
public ResultSet doQuery(final SqlContext sqlContext, final PreparedStatement preparedStatement,
		final ResultSet resultSet) {
	// カウント初期値
	int rowCount = -1;
	try {
		// resultSetのカーソル種別を取得
		// 種別「TYPE_FORWARD_ONLY」の場合、beforeFirstメソッドが効かないため除外
		if (resultSet.getType() != ResultSet.TYPE_FORWARD_ONLY) {
			// 件数結果取得
			resultSet.last();
			rowCount = resultSet.getRow();
			resultSet.beforeFirst();
		}
	} catch (SQLException e) {
		// ここでの例外は実処理に影響を及ぼさないよう握りつぶす
	}

	String userName = getParam(sqlContext, USER_NAME_KEY);
	if (userName == null) {
		// ユーザ名が設定されていない時
		userName = DEFAULT_USER_NAME;
	}

	String funcId = getParam(sqlContext, FUNC_ID_KEY);
	if (funcId == null) {
		// 機能IDが設定されていない時
		funcId = DEFAULT_FUNC_ID;
	}

	LOG.debug(ToStringBuilder.reflectionToString(
			new AuditData(userName, funcId, sqlContext.getSqlId(), sqlContext.getSqlName(), sqlContext
					.getExecutableSql(), rowCount), ToStringStyle.JSON_STYLE));

	return resultSet;
}
 
Example 6
Project: AeroStory   File: MaplePacketCreator.java   View Source Code Vote up 6 votes
public static byte[] BBSThreadList(ResultSet rs, int start) throws SQLException {
    final MaplePacketLittleEndianWriter mplew = new MaplePacketLittleEndianWriter();
    mplew.writeShort(SendOpcode.GUILD_BBS_PACKET.getValue());
    mplew.write(0x06);
    if (!rs.last()) {
        mplew.write(0);
        mplew.writeInt(0);
        mplew.writeInt(0);
        return mplew.getPacket();
    }
    int threadCount = rs.getRow();
    if (rs.getInt("localthreadid") == 0) { //has a notice
        mplew.write(1);
        addThread(mplew, rs);
        threadCount--; //one thread didn't count (because it's a notice)
    } else {
        mplew.write(0);
    }
    if (!rs.absolute(start + 1)) { //seek to the thread before where we start
        rs.first(); //uh, we're trying to start at a place past possible
        start = 0;
    }
    mplew.writeInt(threadCount);
    mplew.writeInt(Math.min(10, threadCount - start));
    for (int i = 0; i < Math.min(10, threadCount - start); i++) {
        addThread(mplew, rs);
        rs.next();
    }
    return mplew.getPacket();
}
 
Example 7
Project: ClassroomFlipkart   File: getUserName.java   View Source Code Vote up 6 votes
public static String[] getUserName(String mailId) {
    String[] name={"",""};

    Connection con = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;

    String query = DBUtils.prepareSelectQuery(" * ",
            "classroomflipkart.userdetail",
            " emailId = '"+mailId+"' ",
            "" );

    try {
        con = DBUtils.getConnection();
        stmt = con.prepareStatement(query);
        rs = stmt.executeQuery();

        rs.last();
        int size = rs.getRow();

        if (size>0){
            rs.beforeFirst();
            rs.next();
            name[0] = rs.getString("name");
            name[1] = rs.getString("certifiedUser");
        }
        else
            name[0] = "";

    } catch (Exception e) {
        name[0] = e.getMessage();
        e.printStackTrace();
    } finally {
        DBUtils.closeAll(rs, stmt, con);
        return name;
    }
}
 
Example 8
Project: dev-courses   File: TestViewAsterisks.java   View Source Code Vote up 6 votes
/**
 *  ensures the content of a given table matches a given object array's content
 */
private void ensureTableContent(String tableName,
                                Object[][] tableData) throws SQLException {

    ResultSet lhs = m_statement.executeQuery("SELECT * FROM \""
        + tableName + "\"");
    ResultSetMetaData meta     = lhs.getMetaData();
    int               colCount = meta.getColumnCount();

    while (lhs.next()) {
        int row = lhs.getRow();

        assertEquals(colCount, tableData[row - 1].length);

        for (int col = 1; col <= colCount; ++col) {
            assertEquals(
                "unexpected table content in " + tableName + " (row "
                + row + ", col " + col + ")", tableData[row - 1][col - 1],
                                              lhs.getObject(col));
        }
    }
}
 
Example 9
Project: ClassroomFlipkart   File: getCategories.java   View Source Code Vote up 6 votes
public static String[] getCategories() {
    String[] category = {"ongoing"};

    Connection con = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;

    String query = DBUtils.prepareSelectQuery(" * ",
            "classroomflipkart.category",
            "",
            "GROUP BY category");

    try {
        con = DBUtils.getConnection();
        stmt = con.prepareStatement(query);
        rs = stmt.executeQuery();

        rs.last();
        int size = rs.getRow();

        if (size>0){
            rs.beforeFirst();

            int count = 0;
            category = new String[size];

            while (rs.next())
                category[count++] = rs.getString("category");
        }

    } catch (Exception e) {
        category[0] = e.getMessage();
        e.printStackTrace();
    } finally {
        DBUtils.closeAll(rs, stmt, con);
        return category;
    }
}
 
Example 10
Project: GameProject-V1.0Beta   File: MyFavoriteDao.java   View Source Code Vote up 6 votes
/**
 * 
 * @param serverIp
 * @param userServerId
 * @param userId
 * @return
 */
public Boolean isFavoriteExistes(String serverIp, String userServerId, String userId) {
	Connection conn = JdbcHelper.getJdbcHelper().getConnection();
	PreparedStatement ps = null;
	ResultSet rs = null;
	
	try {
		if(null != conn) {
			String sql = "select m.* from myfavorites m where m.USERID=? and m.USERSERVERID=? and m.SERVERIP=?;";
			ps = conn.prepareStatement(sql);
			ps.setString(1, userId);
			ps.setString(2, userServerId);
			ps.setString(3, serverIp);
			
			rs = ps.executeQuery();
			
			if(null == rs)
				return null;
			rs.last();
			System.out.println(rs.getRow());
			if(0 < rs.getRow())
				return true;
			return false;
		}
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		System.out.println("sql state: " + e.getSQLState() +
				" --> " + e.getStackTrace() + "  -->" + e.getMessage());
		return null;
	}
	return null;
}
 
Example 11
Project: sjk   File: AppRankDaoImpl.java   View Source Code Vote up 6 votes
@Override
public List<App> getAppCategoryRank(final int parentId, final int subCatalog, final int top) {
    PreparedStatementCallback<List<App>> cb = new PreparedStatementCallback<List<App>>() {
        @Override
        public List<App> doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.setInt(1, parentId);
            ps.setInt(2, subCatalog);
            ps.setInt(3, top);
            ResultSet rs = null;
            try {
                rs = ps.executeQuery();
                if (rs.last()) {
                    int count = rs.getRow();
                    List<App> list = new ArrayList<App>(count);
                    rs.beforeFirst();
                    App app = null;
                    while (rs.next()) {
                        app = appRowMapper.mapRow(rs, rs.getRow());
                        changeOutputImpl.setUrls(app);
                        list.add(app);
                    }
                    return list;
                }

            } catch (Exception e) {
                logger.error("SQL data error:", e);
                return null;
            } finally {
                if (null != rs)
                    rs.close();
            }
            return null;
        }
    };
    return jdbcTemplate.execute(QUERY_APP_CATEGORY_TOP_SQL, cb);
}
 
Example 12
Project: sjk   File: AppsDaoImpl.java   View Source Code Vote up 5 votes
@Override
public List<App> findByIds(List<Integer> ids) {
    // Session session = sessions.getCurrentSession();
    // Query query = null;
    // query =
    // session.createQuery("select a.id, a.name, a.downLoadLink, a.logo from App a where id in (:ids)").setParameterList("ids",
    // ids);
    // List<App> list = HibernateHelper.list(query);
    // for (App app : list) {
    // changeOutputImpl.setUrls(app);
    // }
    StringBuilder tmp = new StringBuilder(ids.size() * 6);
    for (Integer id : ids) {
        tmp.append(id).append(',');
    }
    tmp.deleteCharAt(tmp.length() - 1);
    String sql = appsByIds.replace("?", tmp.toString());

    PreparedStatementCallback<List<App>> cb = new PreparedStatementCallback<List<App>>() {
        @Override
        public List<App> doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ResultSet rs = null;
            try {
                rs = ps.executeQuery();
                if (rs.last()) {
                    int count = rs.getRow();
                    List<App> list = new ArrayList<App>(count);
                    rs.beforeFirst();
                    App app = null;
                    while (rs.next()) {
                        app = appsRowMapper.mapRow(rs, rs.getRow());
                        changeOutputImpl.setUrls(app);
                        list.add(app);
                    }
                    return list;
                } else {
                    return null;
                }
            } finally {
                if (null != rs) {
                    rs.close();
                }
            }
        }

    };
    return this.jdbcTemplate.execute(sql, cb);
}
 
Example 13
Project: JITRAX   File: DatabaseComparator.java   View Source Code Vote up 5 votes
private boolean databaseSchemasCoincide() {
	
	try {
		// For each DBMS table
		tablesResultSet.beforeFirst();
		while (tablesResultSet.next()) {
			// Getting tables
			String tableName = tablesResultSet.getString("TABLE_NAME");
			Table currentLocalTable = getDatabase().getTableByName(tableName);
			int numberOfAttributesForRemote = 0;
			
			if (currentLocalTable != null) {
			
				// Getting attributes
				ResultSet attrResultSet = databaseMetadata.getColumns(null, null, tableName, "%");
				
				// Getting the number of rows returned (number of attributes in the current table)
				// and storing it in the 'numberOfAttributesForRemote'
				if (attrResultSet != null) {  
				  attrResultSet.beforeFirst();  
				  attrResultSet.last();  
				  numberOfAttributesForRemote = attrResultSet.getRow();
				  attrResultSet.beforeFirst();
				}
				
				// If the number of attributes differs, databases are not compatibles
				if (currentLocalTable.getNumOfColumns() != numberOfAttributesForRemote) {
					return false;
				}
				
				// COMPARING ATTRIBUTES
				while (attrResultSet.next()) {
					String attrName = attrResultSet.getString("COLUMN_NAME");
					String attrType = attrResultSet.getString("TYPE_NAME");
					DataType attrDataType;
					
					// Comparing data types
					if (attrType.contains("varchar")) {
						attrDataType = DataType.STRING;
					} else if (attrType.contains("char")) {
						attrDataType = DataType.CHAR;
					} else if (attrType.contains("int")) {
						attrDataType = DataType.INT;
					} else if (attrType.contains("float")) {
						attrDataType = DataType.FLOAT;
					} else if (attrType.contains("date")) {
						attrDataType = DataType.DATE;
					} else {
						attrDataType = null;
					}
					
					// Check if the attribute exists on the current table
					if (!currentLocalTable.attributeExists(attrName, attrDataType)) {
						return false;
					}
				}
			}
		}
		
		tablesResultSet.isBeforeFirst();
	}
	
	catch (SQLException e) {
		e.printStackTrace();
	}
		
	return true;
}
 
Example 14
Project: Locked   File: SQLUtil.java   View Source Code Vote up 5 votes
public static boolean tableExists(SQLConnection connection, String table) throws ClassNotFoundException, SQLException {
    checkAndOpen(connection);
    Connection c = connection.getConnection();
    DatabaseMetaData metaData = c.getMetaData();
    ResultSet rs = metaData.getTables(null, null, table, null);
    if (rs.next()) {
        return rs.getRow() == 1;
    }
    return false;
}
 
Example 15
Project: elastic-db-tools-for-java   File: MultiShardResultSet.java   View Source Code Vote up 5 votes
@Override
public int getRow() throws SQLException {
    int currentRow = this.getCurrentResultSet() == null ? 0 : this.getCurrentResultSet().getRow();
    int totalRowsOfPreviousResultSets = 0;
    if (currentIndex - 2 >= 0) {
        int index = currentIndex - 2;
        for (; index >= 0; index--) {
            ResultSet set = results.get(index).getResultSet();
            set.last();
            totalRowsOfPreviousResultSets += set.getRow();
        }
    }
    return currentRow + totalRowsOfPreviousResultSets;
}
 
Example 16
Project: rapidminer   File: DatabaseDataRow.java   View Source Code Vote up 4 votes
/**
 * Creates a data row from the given result set. The current row of the result set if used as
 * data source.
 */
public DatabaseDataRow(ResultSet resultSet) throws SQLException {
	this.resultSet = resultSet;
	this.row = resultSet.getRow();
}
 
Example 17
Project: OpenDiabetes   File: TestCollation.java   View Source Code Vote up 4 votes
/**
 * checks sorting a table with according to a given collation
 */
protected String checkSorting(String collationName) {

    String stmt1 = "DROP TABLE WORDLIST IF EXISTS;";
    String stmt2 =
        "CREATE TEXT TABLE WORDLIST ( ID INTEGER, WORD VARCHAR(50) );";
    String stmt3 = "SET TABLE WORDLIST SOURCE \"" + collationName
                   + ".csv;encoding=UTF-8\"";
    String selectStmt    = "SELECT ID, WORD FROM WORDLIST ORDER BY WORD";
    String returnMessage = "";

    try {

        // set database collation
        statement.execute(getSetCollationStmt(collationName));
        statement.execute(stmt1);
        statement.execute(stmt2);
        statement.execute(stmt3);

        ResultSet results = statement.executeQuery(selectStmt);

        while (results.next()) {
            int expectedPosition = results.getInt(1);
            int foundPosition    = results.getRow();

            if (expectedPosition != foundPosition) {
                String word = results.getString(2);

                return "testing collation '" + collationName
                       + "' failed\n" + "  word              : " + word
                       + "\n" + "  expected position : "
                       + expectedPosition + "\n"
                       + "  found position    : " + foundPosition + "\n";
            }
        }
    } catch (SQLException e) {
        return "testing collation '" + collationName
               + "' failed\n  exception message: " + e.getMessage() + "\n";
    }

    return "";
}
 
Example 18
Project: dev-courses   File: TestCollation.java   View Source Code Vote up 4 votes
/**
 * checks sorting a table with according to a given collation
 */
protected String checkSorting(String collationName) {

    String stmt1 = "DROP TABLE WORDLIST IF EXISTS;";
    String stmt2 =
        "CREATE TEXT TABLE WORDLIST ( ID INTEGER, WORD VARCHAR(50) );";
    String stmt3 = "SET TABLE WORDLIST SOURCE \"" + collationName
                   + ".csv;encoding=UTF-8\"";
    String selectStmt    = "SELECT ID, WORD FROM WORDLIST ORDER BY WORD";
    String returnMessage = "";

    try {

        // set database collation
        statement.execute(getSetCollationStmt(collationName));
        statement.execute(stmt1);
        statement.execute(stmt2);
        statement.execute(stmt3);

        ResultSet results = statement.executeQuery(selectStmt);

        while (results.next()) {
            int expectedPosition = results.getInt(1);
            int foundPosition    = results.getRow();

            if (expectedPosition != foundPosition) {
                String word = results.getString(2);

                return "testing collation '" + collationName
                       + "' failed\n" + "  word              : " + word
                       + "\n" + "  expected position : "
                       + expectedPosition + "\n"
                       + "  found position    : " + foundPosition + "\n";
            }
        }
    } catch (SQLException e) {
        return "testing collation '" + collationName
               + "' failed\n  exception message: " + e.getMessage() + "\n";
    }

    return "";
}
 
Example 19
Project: ClassroomFlipkart   File: fetchComments.java   View Source Code Vote up 4 votes
public static VBox fetchComments(String productId) {

        VBox comments = new VBox();

        Connection con = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        String query = DBUtils.prepareSelectQuery(" * ",
                " classroomflipkart.productcoment ",
                "productId = '"+productId+"' ",
                "ORDER BY timestamp desc");

        try {
            con = DBUtils.getConnection();
            stmt = con.prepareStatement(query);
            rs = stmt.executeQuery();

            rs.last();
            int size = rs.getRow();

            if (size>0) {
                rs.beforeFirst();
                while (rs.next()){
                    String productRating = rs.getString("productRating");
                    String productComent = rs.getString("productComent");
                    String emailId = rs.getString("emailId");
                    String timestamp = rs.getString("timestamp");

                    comments.getChildren().add(comment(productRating,productComent,emailId, timestamp));
                }
            }

        } catch (Exception e) {
            comments.getChildren().add(new Label(e.getMessage()));
            e.printStackTrace();
        } finally {
            DBUtils.closeAll(rs, stmt, con);
            return comments;
        }
    }
 
Example 20
Project: GameProject-V1.0Beta   File: MyFavoriteDao.java   View Source Code Vote up 4 votes
/**
 * 
 * @param userId
 * @param userServerId
 * @return
 */
public List<MyFavorite> queryMyFavoriteWithGameUser(String userId, String userServerId){
	Connection conn = JdbcHelper.getJdbcHelper().getConnection();
	PreparedStatement ps = null;
	ResultSet rs = null;
	List<MyFavorite> list = new ArrayList<MyFavorite>();
	try {
		if(null != conn) {
			String sql = "select m.* from myfavorites m where m.USERID=? and m.USERSERVERID=?;";
			ps = conn.prepareStatement(sql);
			ps.setString(1, userId);
			ps.setString(2, userServerId);
			
			rs = ps.executeQuery();
			
			if(null == rs)
				return null;
			rs.last();
			System.out.println(rs.getRow());
			if(0 == rs.getRow())
				return null;
			rs.beforeFirst();
			
			while(rs.next()) {
				MyFavorite m = new MyFavorite();
				m.setUserId(rs.getString(1));
				m.setUserServerId(rs.getString(2));
				m.setServerIP(rs.getString(3));
				list.add(m);
			}
			
			return list;
		}
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		System.out.println("sql state: " + e.getSQLState() +
				" --> " + e.getStackTrace() + "  -->" + e.getMessage());
		return null;
	}
	return null;
}