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

The following are Jave code examples for showing how to use first() 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: GamingPlatform   File: RecensioneDao.java   View Source Code Vote up 6 votes
/**
 *Method to find a review thanks to user and game
 *
 *@param utente user who made review
 *@param gioco reviewed game
 *@return Recensione searched review
 *@throws SQLException if no database connection is found or another error occurs
 */
 @Override
 public Recensione findReviewByUserAndGame(Utente utente, Gioco gioco) throws SQLException{
   Recensione recensione;
   Connection connection = DB.openConnection();
   PreparedStatement ps = connection.prepareStatement(FIND_REVIEW_BY_USER_AND_GAME);
   ps.setInt(1, utente.getId());
   ps.setInt(2, gioco.getId());
   ResultSet rset = ps.executeQuery();
   if ( rset.first() == false ) 
return null;
   recensione = new Recensione(rset.getInt(1), rset.getInt(2), rset.getString(3), rset.getInt(4), rset.getInt(5));
   ps.close();
   connection.close();
   return recensione;
 }
 
Example 2
Project: orbis-lps2ima-dev   File: BaseServerImpl.java   View Source Code Vote up 6 votes
/**
 * Test if the user name and password are correct.
 * @param username Name of the user.
 * @param password Password of the user.
 * @return True if the user is correct, false otherwise.
 */
private boolean testUser(String username, String password){
    try {
        PreparedStatement ps = ds.getConnection().prepareStatement(
                "SELECT COUNT(username) FROM session_table WHERE username LIKE ? AND password LIKE ?;");
        ps.setString(1, username);
        ps.setString(2, password);
        ResultSet rs = ps.executeQuery();
        rs.first();
        boolean isUser = rs.getInt(1) != 0;
        rs.close();
        return isUser;
    } catch (SQLException e) {
        LOGGER.error("Unable to request the database in order to test username/password.\n"+e.getLocalizedMessage());
        for(StackTraceElement el : e.getStackTrace()){
            LOGGER.error(el.toString());
        }
    }
    return false;
}
 
Example 3
Project: orbis-lps2ima-dev   File: BaseServerImpl.java   View Source Code Vote up 6 votes
/**
 * Test if the user name is correct.
 * @param username Name of the user.
 * @return True if the user is correct, false otherwise.
 */
private boolean testUser(String username){
    try {
        PreparedStatement ps = ds.getConnection().prepareStatement(
                "SELECT COUNT(username) FROM session_table WHERE username LIKE ?;");
        ps.setString(1, username);
        ResultSet rs = ps.executeQuery();
        rs.first();
        boolean isUser = rs.getInt(1) != 0;
        rs.close();
        return isUser;
    } catch (SQLException e) {
        LOGGER.error("Unable to request the database in order to test username.\n"+e.getLocalizedMessage());
        for(StackTraceElement el : e.getStackTrace()){
            LOGGER.error(el.toString());
        }
    }
    return false;
}
 
Example 4
Project: GamingPlatform   File: UtenteDao.java   View Source Code Vote up 6 votes
/**
*Method to check if a user has already review a game
*
*@param utente user who reviews
*@param gioco reviewed game
*@return  boolean true if the user has already reviewed the game, false otherwise
*@throws SQLException if no database connection is found or another error occurs
*/
@Override
public boolean reviewAlreadyMadeByUser(Utente utente, Gioco gioco) throws SQLException{
  boolean already_reviewed = false;
  Connection connection = DB.openConnection();
  PreparedStatement ps = connection.prepareStatement(GAME_ALREADY_REVIEWED);
  ps.setInt(1, utente.getId());
  ps.setInt(2, gioco.getId());
  ResultSet rset = ps.executeQuery();
  rset.first();
  if( rset.getInt(1) == 1 )
      already_reviewed = true;
  ps.close();
  rset.close();
  connection.close();
  return already_reviewed;
}
 
Example 5
Project: uclan-messanger   File: AuthenticationProvider.java   View Source Code Vote up 6 votes
public User getUser(User user) throws Exception {
    try {
        connect();            
        String sql = String.format("CALL get_user('%s', '%s', '%s');", user.getEmail(), user.getUserName(), user.getPassword());
        statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        if(resultSet.first()) {
            user.setId(resultSet.getInt("Id"));
            user.setEmail(resultSet.getString("Email"));
            user.setUserName(resultSet.getString("UserName"));
            user.setPassword("");
        } else {
            user = null;
        }
        disconnect();
        return user;
    } catch (Exception e) {
        throw new Exception("error occured while getting the user data!");
    }        
}
 
Example 6
Project: uclan-messanger   File: AuthenticationProvider.java   View Source Code Vote up 6 votes
public User getUserWithUsername(User newUser) throws Exception {
    try {
        connect();            
        String sql = String.format("SELECT * FROM Users WHERE UserName='%s'", newUser.getUserName());
        statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        User user = new User();
        if(resultSet.first()) {
            user.setId(resultSet.getInt("Id"));
            user.setEmail(resultSet.getString("Email"));
            user.setUserName(resultSet.getString("UserName"));
            user.setPassword("");
        } else {
            user = null;
        }
        disconnect();
        return user;
    } catch (Exception e) {
        throw new Exception("error occured while getting the user data!");
    }        
}
 
Example 7
Project: GamingPlatform   File: UtenteDao.java   View Source Code Vote up 6 votes
/**
*Method to check if a user has already voted a game
*
*@param utente user who votes
*@param gioco voted game
*@return  boolean true if the user has already voted the game, false otherwise
*@throws SQLException if no database connection is found or another error occurs
*/
@Override
public boolean gameAlreadyVotedByUser(Utente utente, Gioco gioco) throws SQLException{
  boolean already_voted = false;
  Connection connection = DB.openConnection();
  PreparedStatement ps = connection.prepareStatement(GAME_ALREADY_VOTED);
  ps.setInt(1, utente.getId());
  ps.setInt(2, gioco.getId());
  ResultSet rset = ps.executeQuery();
  rset.first();
  if( rset.getInt(1) == 1 )
      already_voted = true;
  ps.close();
  rset.close();
  connection.close();
  return already_voted;
}
 
Example 8
Project: lams   File: ToolDBUpdater.java   View Source Code Vote up 6 votes
public String queryTool(String toolSig, String column) {
Connection conn = getConnection();
PreparedStatement stmt = null;
ResultSet results = null;
try {
    stmt = conn
	    .prepareStatement("select " + column + " from lams_tool where tool_signature= \"" + toolSig + "\"");
    System.out.println("SQL stmt: " + stmt);
    results = stmt.executeQuery();

    if (results.first()) {
	return results.getString(column);

    }
} catch (SQLException se) {

    throw new DeployException("Could not get entry from lams_tool: " + column + "\n" + se.getMessage());

} finally {
    DbUtils.closeQuietly(stmt);
}
return "ERROR";
   }
 
Example 9
Project: OnlineChecker-Spigot-SQL-Support   File: SQLUtil.java   View Source Code Vote up 5 votes
public String getFirstJoined(UUID uuid) {
	try {
		ResultSet resultset = table.select().where("uuid", uuid.toString()).execute();
		resultset.first();
		return resultset.getString("firstjoined");
	} catch (SQLException e) {
		return null;
	}
}
 
Example 10
Project: uclan-messanger   File: MessageProvider.java   View Source Code Vote up 5 votes
public Message add(Message message) throws Exception {
    try {
        connect();
        String sql;
        
        if(message.getId() <= 0) {
            sql = String.format("CALL add_message('%d', '%s', '%d');", message.getUserId(), message.getMessage(), message.getIsPublic() ? 1 : 0);
        } else {
            sql = String.format("CALL update_message('%d', '%s', '%d');", message.getId(), message.getMessage(), message.getIsPublic() ? 1 : 0);
        }
        
        statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        if(resultSet.first()) {
            message.setId(resultSet.getInt("Id"));
            message.setUserId(resultSet.getInt("UserId"));
            message.setMessage(resultSet.getString("Message"));
            message.setIsPublic(resultSet.getBoolean("IsPublic"));
        } else {
            message = null;
        }
        disconnect();
        return message;
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("error occured while saving the message data!");
    }
}
 
Example 11
Project: GamingPlatform   File: RecensioneDao.java   View Source Code Vote up 5 votes
/**
 *Method to find a review thanks to its id
 *
 *@param id review's id
 *@return Recensione searched review
 *@throws SQLException if no database connection is found or another error occurs
 */
 @Override
 public Recensione findReviewById(int id) throws SQLException{
   Recensione recensione;
   Connection connection = DB.openConnection();
   PreparedStatement ps = connection.prepareStatement(FIND_REVIEW);
   ps.setInt(1, id);
   ResultSet rset = ps.executeQuery();
   if ( rset.first() == false )
return null;
   recensione = new Recensione(rset.getInt(1), rset.getInt(2), rset.getString(3), rset.getInt(4), rset.getInt(5));
   ps.close();
   connection.close();
   return recensione;
 }
 
Example 12
Project: KernelHive   File: H2Persistance.java   View Source Code Vote up 5 votes
public void prepareTable(H2Entity entity) throws H2PersistanceException {
	try {
		ResultSet result = connection.createStatement().executeQuery(String.format("SELECT * \n"
				+ "                 FROM INFORMATION_SCHEMA.TABLES \n"
				+ "                 WHERE TABLE_SCHEMA = 'PUBLIC' \n"
				+ "                 AND  TABLE_NAME = '%s'", entity.getTableName().toUpperCase()));
		if (!result.first()) {
			createTable(entity);
		}
	} catch (SQLException ex) {
		logger.log(Level.SEVERE,
				String.format("Cannot check if %s exists", entity.getTableName()), ex);
	}
}
 
Example 13
Project: IP1   File: User.java   View Source Code Vote up 5 votes
public void setUserId(String email) {
    ResultSet rs = connector.executeSelectStatement("SELECT id FROM users WHERE users.email LIKE '" + email + "'");
    try {
        rs.first();
        Main.setId(rs.getInt("id"));
    } catch (SQLException ex) {
        Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
    }
    
}
 
Example 14
Project: eXperDB-DB2PG   File: DBUtils.java   View Source Code Vote up 5 votes
public static String getCreateTableQuery(String table,String srcPoolName, DBConfigInfo dbConfigInfo) {
	Connection srcConn = null;
	PreparedStatement srcPreStmt = null;
	String createTableQuery = null;
	QueryMaker qm = new QueryMaker("/src_mapper.xml");
	Map<String,Object> params = new HashMap<String,Object>();
	try {
		LogUtils.info("[START_CREATE_TABLE_QUERY_MAKE] "+table,DBUtils.class);
		srcConn = DBCPPoolManager.getConnection(srcPoolName);
		if(dbConfigInfo.DB_TYPE.equals(Constant.DB_TYPE.MYSQL)) {
			if(dbConfigInfo.SCHEMA_NAME!=null && !dbConfigInfo.SCHEMA_NAME.equals("")) {
				params.put("SCHEMA", dbConfigInfo.SCHEMA_NAME+".");
			} else {
				params.put("SCHEMA", "");
			}
			if(table!=null && !table.equals("")) {
				params.put("TABLE", table);
			} else {
				throw new Exception("TABLE NOT FOUND");
			}
			srcPreStmt = qm.getPreparedStatement("GET_CREATE_TABLE",Constant.DB_TYPE.MYSQL, params, srcConn, Double.parseDouble(dbConfigInfo.DB_VER));
			ResultSet rs = srcPreStmt.executeQuery();
			if(rs.first()) createTableQuery = rs.getString("Create Table");
			rs.close();
		}
		srcConn.close();
	} catch(Exception e){
		LogUtils.error(e.getMessage(),DBUtils.class);
	} finally {
		LogUtils.info("[END_CREATE_TABLE_QUERY_MAKE] "+table,DBUtils.class);
	}
	return createTableQuery;
}
 
Example 15
Project: ProyectoPacientes   File: ConnectionRegressionTest.java   View Source Code Vote up 5 votes
private boolean isResultSetClosedForTestBug69746(ResultSet resultSet) {
    try {
        resultSet.first();
    } catch (SQLException ex) {
        return ex.getMessage().equalsIgnoreCase(Messages.getString("ResultSet.Operation_not_allowed_after_ResultSet_closed_144"));
    }
    return false;
}
 
Example 16
Project: swing-memory-game   File: BestScoreRepository.java   View Source Code Vote up 5 votes
/**
 * Find one item by id.
 *
 * @param id
 * @return
 */
@Override
public BestScoreBean find(long id)
{
    log.debug("Start method...");

    BestScoreBean obj = null;

    try
    {
        PreparedStatement prepared = DAOConnection.getInstance().prepareStatement(
                "SELECT * FROM best_scores WHERE id=?");

        prepared.setLong(1, id);

        ResultSet result = prepared.executeQuery();

        if (result.first())
        {
            obj = map(result);
        }

    } catch (SQLException e)
    {
        log.error("Error finding product : " + e);
    }

    log.debug("End method.");

    return obj;
}
 
Example 17
Project: IP1   File: User.java   View Source Code Vote up 5 votes
public boolean isLoginCorrect(String email, String password) {
    try {
        ResultSet rs = connector.executeSelectStatement("SELECT password FROM users WHERE users.email LIKE '" + email + "'");
        if(rs.isBeforeFirst()) {
            rs.first();
            return rs.getString("password").equals(password);
        }
        return false;
    } catch (SQLException ex) {
        Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}
 
Example 18
Project: OnlineChecker-Spigot-SQL-Support   File: SQLUtil.java   View Source Code Vote up 5 votes
public void generateAccount(Player p) {
	try {
		if (!exists(p.getUniqueId())) {
			table.insert().insert("uuid").value(p.getUniqueId().toString()).execute();
			setFirstJoined(p.getUniqueId(), Long.toString(p.getFirstPlayed()));
			table.update().set("name", p.getPlayerListName())
					.where("uuid", p.getUniqueId().toString())
					.execute();
			return;
		} else {
			ResultSet res = table.select().where("uuid", p.getUniqueId().toString()).execute();
			res.first();
			String s = res.getString("name");
			if (s == null) {
				table.update().set("name", p.getName()).where("uuid", p.getUniqueId().toString())
						.execute();
				return;
			}
			if (!s.equals(p.getName())) {
				table.update().set("name", p.getName()).where("uuid", p.getUniqueId().toString())
						.execute();
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 19
Project: the-vigilantes   File: StatementRegressionTest.java   View Source Code Vote up 4 votes
public void testBug36478() throws Exception {

        createTable("testBug36478", "(`limit` varchar(255) not null primary key, id_limit INT, limit1 INT, maxlimit2 INT)");

        this.stmt.execute("INSERT INTO testBug36478 VALUES ('bahblah',1,1,1)");
        this.stmt.execute("INSERT INTO testBug36478 VALUES ('bahblah2',2,2,2)");
        this.pstmt = this.conn.prepareStatement("select 1 FROM testBug36478");

        this.pstmt.setMaxRows(1);
        this.rs = this.pstmt.executeQuery();
        this.rs.first();
        assertTrue(this.rs.isFirst());
        assertTrue(this.rs.isLast());

        this.pstmt = this.conn.prepareStatement("select `limit`, id_limit, limit1, maxlimit2 FROM testBug36478");
        this.pstmt.setMaxRows(0);
        this.rs = this.pstmt.executeQuery();
        this.rs.first();
        assertTrue(this.rs.isFirst());
        assertFalse(this.rs.isLast());

        //SSPS
        Connection _conn = null;
        PreparedStatement s = null;
        try {
            Properties props = new Properties();
            props.setProperty("useServerPrepStmts", "true");

            _conn = getConnectionWithProps(props);
            s = _conn.prepareStatement("select 1 FROM testBug36478");

            s.setMaxRows(1);
            ResultSet _rs = s.executeQuery();
            _rs.first();
            assertTrue(_rs.isFirst());
            assertTrue(_rs.isLast());

            s = _conn.prepareStatement("select `limit`, id_limit, limit1, maxlimit2 FROM testBug36478");
            s.setMaxRows(0);
            _rs = s.executeQuery();
            _rs.first();
            assertTrue(_rs.isFirst());
            assertFalse(_rs.isLast());

        } finally {
            if (s != null) {
                s.close();
            }
            if (_conn != null) {
                _conn.close();
            }
        }

    }
 
Example 20
Project: ProyectoPacientes   File: StatementRegressionTest.java   View Source Code Vote up 4 votes
public void testBug36478() throws Exception {

        createTable("testBug36478", "(`limit` varchar(255) not null primary key, id_limit INT, limit1 INT, maxlimit2 INT)");

        this.stmt.execute("INSERT INTO testBug36478 VALUES ('bahblah',1,1,1)");
        this.stmt.execute("INSERT INTO testBug36478 VALUES ('bahblah2',2,2,2)");
        this.pstmt = this.conn.prepareStatement("select 1 FROM testBug36478");

        this.pstmt.setMaxRows(1);
        this.rs = this.pstmt.executeQuery();
        this.rs.first();
        assertTrue(this.rs.isFirst());
        assertTrue(this.rs.isLast());

        this.pstmt = this.conn.prepareStatement("select `limit`, id_limit, limit1, maxlimit2 FROM testBug36478");
        this.pstmt.setMaxRows(0);
        this.rs = this.pstmt.executeQuery();
        this.rs.first();
        assertTrue(this.rs.isFirst());
        assertFalse(this.rs.isLast());

        //SSPS
        Connection _conn = null;
        PreparedStatement s = null;
        try {
            Properties props = new Properties();
            props.setProperty("useServerPrepStmts", "true");

            _conn = getConnectionWithProps(props);
            s = _conn.prepareStatement("select 1 FROM testBug36478");

            s.setMaxRows(1);
            ResultSet _rs = s.executeQuery();
            _rs.first();
            assertTrue(_rs.isFirst());
            assertTrue(_rs.isLast());

            s = _conn.prepareStatement("select `limit`, id_limit, limit1, maxlimit2 FROM testBug36478");
            s.setMaxRows(0);
            _rs = s.executeQuery();
            _rs.first();
            assertTrue(_rs.isFirst());
            assertFalse(_rs.isLast());

        } finally {
            if (s != null) {
                s.close();
            }
            if (_conn != null) {
                _conn.close();
            }
        }

    }