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

The following are Jave code examples for showing how to use beforeFirst() 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: jdk8u-jdk   File: CommonRowSetTests.java   View Source Code Vote up 8 votes
protected int displayResults(ResultSet rs) throws SQLException {
    int rows = 0;
    ResultSetMetaData rsmd = rs.getMetaData();
    int cols = rsmd.getColumnCount();
    if (rs != null) {
        rs.beforeFirst();
        while (rs.next()) {
            rows++;

            for (int i = 0; i < cols; i++) {
                System.out.print(rs.getString(i + 1) + " ");
            }
            System.out.println();
        }
    }

    return rows;
}
 
Example 2
Project: zeratul   File: SqlTools.java   View Source Code Vote up 8 votes
private void handleResultSet(List<Map<String, Object>> list, ResultSet resultSet) {
    try {
        if (resultSet != null && resultSet.last()) {
            resultSet.beforeFirst();
            ResultSetMetaData rsmd = resultSet.getMetaData();
            while (resultSet.next()) {
                Map<String, Object> map = Maps.newHashMap();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    map.put(rsmd.getColumnName(i), resultSet.getString(i));
                }
                list.add(map);
            }
            resultSet.beforeFirst();
            resultSet.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example 3
Project: text-readability-analyzer   File: DBInteract.java   View Source Code Vote up 7 votes
/**
 * Prints the supplied results to the console
 * 
 * @param results
 *            ResultSet results from database query
 * @throws SQLException
 *             unable to get query results
 */
private void printResults(ResultSet results) throws SQLException {

	if (!results.next()) {
		System.out.println("\tDatabase Empty");
	} else {
		System.out.println("\t#\tScore:\t\tTitle:");
		System.out.println("\t---\t----------\t----------------------");
		int place = 1;
		results.beforeFirst();
		while (results.next()) {
			System.out.println("\t" + place++ + "\t" + results.getDouble("averageReadability") + "\t\t"
					+ results.getString("title"));
		}
	}
}
 
Example 4
Project: openjdk-jdk10   File: CommonRowSetTests.java   View Source Code Vote up 7 votes
protected int displayResults(ResultSet rs) throws SQLException {
    int rows = 0;
    ResultSetMetaData rsmd = rs.getMetaData();
    int cols = rsmd.getColumnCount();
    if (rs != null) {
        rs.beforeFirst();
        while (rs.next()) {
            rows++;

            for (int i = 0; i < cols; i++) {
                System.out.print(rs.getString(i + 1) + " ");
            }
            System.out.println();
        }
    }

    return rows;
}
 
Example 5
Project: AeroStory   File: MaplePacketCreator.java   View Source Code Vote up 7 votes
public static byte[] showGuildRanks(int npcid, ResultSet rs) throws SQLException {
    final MaplePacketLittleEndianWriter mplew = new MaplePacketLittleEndianWriter();
    mplew.writeShort(SendOpcode.GUILD_OPERATION.getValue());
    mplew.write(0x49);
    mplew.writeInt(npcid);
    if (!rs.last()) { //no guilds o.o
        mplew.writeInt(0);
        return mplew.getPacket();
    }
    mplew.writeInt(rs.getRow()); //number of entries
    rs.beforeFirst();
    while (rs.next()) {
        mplew.writeMapleAsciiString(rs.getString("name"));
        mplew.writeInt(rs.getInt("GP"));
        mplew.writeInt(rs.getInt("logo"));
        mplew.writeInt(rs.getInt("logoColor"));
        mplew.writeInt(rs.getInt("logoBG"));
        mplew.writeInt(rs.getInt("logoBGColor"));
    }
    return mplew.getPacket();
}
 
Example 6
Project: openjdk-jdk10   File: CommonWebRowSetTests.java   View Source Code Vote up 6 votes
@Test(dataProvider = "rowsetUsingCoffees")
public void WebRowSetTest0006(WebRowSet wrs) throws Exception {
    ResultSet rs = wrs;
    rs.beforeFirst();
    ByteArrayOutputStream baos = writeWebRowSetWithOutputStreamWithWriter(rs);
    try (WebRowSet wrs1 = readWebRowSetWithOInputStreamWithReader(baos)) {
        assertEquals(getPrimaryKeys(wrs1), COFFEES_PRIMARY_KEYS);
        assertEquals(wrs1.size(), COFFEES_ROWS);
    }
}
 
Example 7
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 8
Project: sjk   File: AppsDaoImpl.java   View Source Code Vote up 6 votes
@Override
public List<AppType> getAppTypes(final int parentId) {
    PreparedStatementCallback<List<AppType>> cb = new PreparedStatementCallback<List<AppType>>() {
        @Override
        public List<AppType> doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ResultSet rs = null;
            try {
                ps.setInt(1, parentId);
                ps.setInt(2, parentId);
                rs = ps.executeQuery();
                // predicate count.
                if (rs.last()) {
                    int count = rs.getRow();
                    List<AppType> list = new ArrayList<AppType>(count);
                    rs.beforeFirst();
                    AppType appType = null;
                    while (rs.next()) {
                        appType = appTypeRowMapper.mapRow(rs, rs.getRow());
                        list.add(appType);
                    }
                    return list;
                } else {
                    return null;
                }
            } finally {
                if (null != rs) {
                    rs.close();
                }
            }
        }
    };
    return this.jdbcTemplate.execute(appTypes, cb);
}
 
Example 9
Project: jdk8u-jdk   File: CommonWebRowSetTests.java   View Source Code Vote up 6 votes
@Test(dataProvider = "rowsetUsingCoffees")
public void WebRowSetTest0006(WebRowSet wrs) throws Exception {
    ResultSet rs = wrs;
    rs.beforeFirst();
    ByteArrayOutputStream baos = writeWebRowSetWithOutputStreamWithWriter(rs);
    try (WebRowSet wrs1 = readWebRowSetWithOInputStreamWithReader(baos)) {
        assertEquals(getPrimaryKeys(wrs1), COFFEES_PRIMARY_KEYS);
        assertEquals(wrs1.size(), COFFEES_ROWS);
    }
}
 
Example 10
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 11
Project: ProyectoPacientes   File: BaseTestCase.java   View Source Code Vote up 6 votes
protected void assertResultSetLength(ResultSet rset, int len) throws Exception {
    int oldRowPos = rset.getRow();
    rset.last();
    assertEquals("Result set length", len, rset.getRow());
    if (oldRowPos > 0) {
        rset.absolute(oldRowPos);
    } else {
        rset.beforeFirst();
    }
}
 
Example 12
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 13
Project: jdk8u-jdk   File: CommonRowSetTests.java   View Source Code Vote up 6 votes
protected Object[] getPrimaryKeys(ResultSet rs) throws SQLException {
    List<? super Object> result = new ArrayList<>();
    if (rs == null) {
        return null;
    }
    rs.beforeFirst();
    while (rs.next()) {
        result.add(rs.getInt(1));
    }
    return result.toArray();
}
 
Example 14
Project: openjdk-jdk10   File: CommonWebRowSetTests.java   View Source Code Vote up 6 votes
@Test(dataProvider = "rowsetUsingCoffees")
public void WebRowSetTest0004(WebRowSet wrs) throws Exception {
    ResultSet rs = wrs;
    rs.beforeFirst();
    ByteArrayOutputStream baos = writeWebRowSetWithOutputStream(rs);
    try (WebRowSet wrs1 = readWebRowSetWithOInputStream(baos)) {
        assertEquals(getPrimaryKeys(wrs1), COFFEES_PRIMARY_KEYS);
        assertEquals(wrs1.size(), COFFEES_ROWS);
    }
}
 
Example 15
Project: jdk8u-jdk   File: CommonWebRowSetTests.java   View Source Code Vote up 6 votes
@Test(dataProvider = "rowsetUsingCoffees")
public void WebRowSetTest0004(WebRowSet wrs) throws Exception {
    ResultSet rs = wrs;
    rs.beforeFirst();
    ByteArrayOutputStream baos = writeWebRowSetWithOutputStream(rs);
    try (WebRowSet wrs1 = readWebRowSetWithOInputStream(baos)) {
        assertEquals(getPrimaryKeys(wrs1), COFFEES_PRIMARY_KEYS);
        assertEquals(wrs1.size(), COFFEES_ROWS);
    }
}
 
Example 16
Project: ClassroomFlipkart   File: dbLoginCheck.java   View Source Code Vote up 5 votes
public static String[] dbLoginCheck(String emailId, String password) {
    Connection con = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;

    String userID = getMotherboardSN.getMotherboardSN();

    String query = DBUtils.prepareSelectQuery(" * ", "classroomflipkart.userdetail", "( emailId = ? AND password = ? )");

    String updateCurrentUserQuery = DBUtils.prepareInsertQuery("classroomflipkart.currentuser", "id, name, emailId", "?,?,?");

    String[] status = {"ongoing",""};

    try {
        con = DBUtils.getConnection();
        stmt = con.prepareStatement(query);
        stmt.setString(1, emailId);
        stmt.setString(2, password);

        rs = stmt.executeQuery();
        rs.last();
        int size = rs.getRow();
        rs.beforeFirst();

        if (size>0){
            status[0]="success";
            rs.next();
            status[1]=rs.getString("name");

            stmt = con.prepareStatement(updateCurrentUserQuery);
            stmt.setString(1, userID);
            stmt.setString(2, status[1]);
            stmt.setString(3, emailId);
            stmt.executeUpdate();
        }

    } catch (Exception e) {
        e.printStackTrace();
        status[0] = e.getMessage();
    } finally {
        DBUtils.closeAll(rs, stmt, con);
        return status;
    }
}
 
Example 17
Project: ClassroomFlipkart   File: fetchProducts.java   View Source Code Vote up 5 votes
public static BorderPane productbyType(String type) {

        BorderPane products = new BorderPane();
        products.setPadding(new Insets(10,20,10,20));

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

        String query = DBUtils.prepareSelectQuery(" * ",
                " classroomflipkart.productdetail AS T ," +
                        " ( "+ DBUtils.prepareSelectQuery("productId",
                                " classroomflipkart.homeproducts ",
                                "type = '"+type+"'")+
                        " ) AS S",
                " T.productId = S.productId ");

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

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

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

                Label title = new Label(type+"");
                title.setFont(Font.font("Open Sans", FontWeight.BOLD,17));
                title.setPadding(new Insets(10));
                title.setAlignment(Pos.CENTER);

                HBox productList = new HBox(20);
                productList.setAlignment(Pos.CENTER);

                while (rs.next()) {
                    String productId = rs.getString("productId");
                    String productName = rs.getString("productName");
                    String newPrice = rs.getString("newPrice");
                    String oldPrice = rs.getString("oldPrice");
                    String category = rs.getString("category");
                    String subcategory = rs.getString("subcategory");
                    String imageName = rs.getString("imageName");
                    String productAvailability = rs.getString("productAvailability");

                    productList.getChildren().add(productDetail.productByType(productId,productName,newPrice,oldPrice,category,subcategory,imageName, productAvailability));
                }

                ScrollPane proScroller = new ScrollPane(productList);
                proScroller.setFitToHeight(true);
                proScroller.setFitToWidth(true);
                proScroller.setPannable(true);
                proScroller.setPadding(new Insets(0,0,30,0));

                StackPane titlePane = new StackPane(title);
                titlePane.setAlignment(Pos.CENTER);

                StackPane productPane = new StackPane(proScroller);
                productPane.setAlignment(Pos.CENTER);

                products.setTop(titlePane);
                products.setCenter(productPane);
            }


        } catch (Exception e) {
            products.setCenter(new Label(e.getMessage()));
            e.printStackTrace();
        } finally {
            DBUtils.closeAll(rs, stmt, con);
            return products;
        }
    }
 
Example 18
Project: dev-courses   File: TestUpdatableResultSets.java   View Source Code Vote up 5 votes
public void testDeletable2() {

        try {
            Connection c =
                DriverManager.getConnection("jdbc:hsqldb:mem:mytestdb", "SA",
                                            "");
            String createSQL =
                "create table test (num INTEGER PRIMARY KEY, str VARCHAR(25))";
            Statement createStmt = c.createStatement();

            createStmt.execute(createSQL);
            createStmt.close();

            String            ins = "insert into test (num,str) values (?,?)";
            PreparedStatement pStmt = c.prepareStatement(ins);

            for (int i = 0; i < 100; i++) {
                pStmt.setInt(1, i);
                pStmt.setString(2, "String" + i);
                pStmt.execute();
            }

            // there should now be 100 rows in the table
            String select = "SELECT * FROM test";
            PreparedStatement stmt = c.prepareStatement(select,
                ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
            ResultSet rs = stmt.executeQuery();

            rs.beforeFirst();

            while (rs.next()) {
                int num = rs.getInt("num");

                if ((num % 7) == 0) {
                    System.out.println("Deleting row:" + num);
                    rs.deleteRow();
                }
            }

            Statement dropStmt = c.createStatement();

            dropStmt.execute("drop table test;");
            dropStmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
Example 19
Project: kibana_sourceforge   File: Load_Data.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws IOException {
    try {
        int max = 1000000;
        Connection connection = DriverManager.getConnection("jdbc:mysql://flossdata.syr.edu:3306", "username", "password");
        // Creates file
        BufferedWriter buffW = new BufferedWriter(Create_file());
        Statement stmt = (Statement) connection.createStatement();

        // Get projects from 2005
        String sql = "SELECT DISTINCT proj_unixname FROM sourceforge.sf_project_status";
        sql += " WHERE date_collected > '2005-01-01' "
                + "AND date_collected < '2005-12-12' "
                + "AND description != 'Inactive' LIMIT 10000;";
        ResultSet projectname = stmt.executeQuery(sql);
        System.out.println("Created project list!");

        if (projectname != null) {
            // Get number of projects
            projectname.last();
            int count = projectname.getRow();
            // Set project list to first position
            projectname.beforeFirst();
            int projectcount = 0;
            // Runs through all projects
            while (projectname.next()) {
                projectcount++;
                if (projectcount==2000)
                    break;
                System.out.println("Skip " + projectcount + " out of " + count);
            }

            while (projectname.next()) {
                projectcount++;
                System.out.println("Processing project " + projectcount + " out of " + count);
                projectname.getString(1);

                // Writes project details in file
                buffW.newLine();
                buffW.write("{\"index\":{\"_index\":\"projects\", \"_type\":\"project\", \"_id\": \"" + projectcount + "\"}}");
                buffW.newLine();
                buffW.write(read_attr(projectname.getString(1), connection));buffW.newLine();

                //Breaks if max is reached
                if (projectcount==max)
                    break;
            }
        }
        //Closes all connections
        buffW.close();
        stmt.close();
        connection.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
 
Example 20
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;
}