Category : Java | Sub Category : Java Programs | By Prasad Bonam Last updated: 2021-04-19 09:13:52 Viewed : 725
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | package runnerdev; import java.sql.*; import java.sql.DriverManager; public class Example { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver" ; static final String DB_URL = "jdbc:mysql://localhost/emp" ; // Database credentials static final String USER = "root" ; static final String PASS = "edureka" ; public static void main(String[] args) { Connection conn = null ; Statement stmt = null ; try { //STEP 2: Register JDBC driver Class.forName( "com.mysql.cj.jdbc.Driver" ); //STEP 3: Open a connection System.out.println( "Connecting to database..." ); conn = DriverManager.getConnection(DB_URL, "root" , "edureka" ); //STEP 4: Execute a query System.out.println( "Creating statement..." ); stmt = conn.createStatement(); String sql; sql = "SELECT id, first, last, age FROM Employees" ; ResultSet rs = stmt.executeQuery(sql); //STEP 5: Extract data from result set while (rs.next()){ //Retrieve by column name int id = rs.getInt( "id" ); int age = rs.getInt( "age" ); String first = rs.getString( "first" ); String last = rs.getString( "last" ); //Display values System.out.print( "ID: " + id); System.out.print( ", Age: " + age); System.out.print( ", First: " + first); System.out.println( ", Last: " + last); } //STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close(); } catch (SQLException se){ //Handle errors for JDBC se.printStackTrace(); } catch (Exception e){ //Handle errors for Class.forName e.printStackTrace(); } finally { //finally block used to close resources try { if (stmt!= null ) stmt.close(); } catch (SQLException se2){ } // nothing can be done try { if (conn!= null ) conn.close(); } catch (SQLException se){ se.printStackTrace(); } //end finally try } //end try System.out.println( "Goodbye!" ); } //end main } // end Example |
On executing the above code, it will establish the connection to the database and retrieve the data present in the database.
1 2 3 4 5 6 7 | Connecting to database... Creating statement... ID: 100 , Age: 18 , First: Zara, Last: Ali ID: 101 , Age: 25 , First: Mahnaz, Last: Fatma ID: 102 , Age: 30 , First: Zaid, Last: Khan ID: 103 , Age: 28 , First: Sumit, Last: Mittal Goodbye! |