Java examples for JDBC:ResultSet
Querying a Database and Retrieving Results
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Main { public static void main(String[] args) { queryDatabase();/*from w ww. j a v a2 s. com*/ } public static void queryDatabase() { String qry = "select idber, recipe_name, description from recipes"; try (Connection conn = getConnection(); Statement stmt = conn.createStatement();) { ResultSet rs = stmt.executeQuery(qry); while (rs.next()) { String recipe = rs.getString("idBER"); String name = rs.getString("RECIPE_NAME"); String desc = rs.getString("DESCRIPTION"); System.out.println(recipe + "\t" + name + "\t" + desc); } } catch (SQLException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { Connection conn = null; String hostname = null; String port = null; String database = null; String username = null; String password = null; String driver = null; String jndi = null; String jdbcUrl; if (driver.equals("derby")) { jdbcUrl = "jdbc:derby://" + hostname + ":" + port + "/" + database; } else { jdbcUrl = "jdbc:oracle:thin:@" + hostname + ":" + port + ":" + database; } conn = DriverManager.getConnection(jdbcUrl, username, password); System.out.println("Successfully connected"); return conn; } }