//STEP 1. Import required packagesimport java.sql.*;publicclassJDBCExample{// JDBC driver name and database URLstaticfinalString JDBC_DRIVER ="com.mysql.jdbc.Driver";staticfinalString DB_URL ="jdbc:mysql://localhost/STUDENTS";// Database credentialsstaticfinalString USER ="username";staticfinalString PASS ="password";publicstaticvoid main(String[] args){Connection conn =null;Statement stmt =null;try{//STEP 2: Register JDBC driverClass.forName("com.mysql.jdbc.Driver");//STEP 3: Open a connectionSystem.out.println("Connecting to a selected database..."); conn =DriverManager.getConnection(DB_URL, USER, PASS);System.out.println("Connected database successfully...");//STEP 4: Execute a querySystem.out.println("Creating statement..."); stmt = conn.createStatement();String sql ="UPDATE Registration "+"SET age = 30 WHERE id in (100, 101)"; stmt.executeUpdate(sql);// Now you can extract all therecords// to see the updated records sql ="SELECT id, first, last, age FROM Registration";ResultSet rs = stmt.executeQuery(sql);while(rs.next()){//Retrieve by column nameint id = rs.getInt("id");int age = rs.getInt("age");String first = rs.getString("first");Stringlast= rs.getString("last");//Display valuesSystem.out.print("ID: "+ id);System.out.print(", Age: "+ age);System.out.print(", First: "+ first);System.out.println(", Last: "+last);} rs.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 resourcestry{if(stmt!=null) conn.close();}catch(SQLException se){}// do nothingtry{if(conn!=null) conn.close();}catch(SQLException se){ se.printStackTrace();}//end finally try}//end trySystem.out.println("Goodbye!");}//end main}
//end JDBCExample
Everything may not be ready met :-) ,i leave some work for you...
Post a Comment