Executando queries

De Basef
Ir para: navegação, pesquisa
  • SELECT - Query parametrizada
try {
   // Query to select users that matches the informed username and password
   String query = "SELECT * FROM users WHERE username = ? AND password = ?";
 
   // Prepares the query
   PreparedStatement ps = conn.prepareStatement( query );
 
   // Passes the parameters values
   ps.setString(1, "usuario");
   ps.setString(2, "senha");
 
   // Executes the query and stores it's result set
   ResultSet rs = ps.executeQuery();
 
   if ( rs.first() ) {         
 
       // One or more records found
       // Reading the username field from the first row
       rs.getString("username");
 
   } else {
 
       // No record was found
 
   }
} catch (SQLException e) {
   System.out.println("Não foi possível executar a Query SQL");
}