15. INSERT en JDBC import java.io.*; import java.sql.*; public class InsertRecords{ public static void main(String[] args) { System.out.println("Insert records example using prepared statement!"); Connection con = null; try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql: //localhost:3306/jdbctutorial","root","root"); try{ String sql = "INSERT movies VALUES(?,?)" ; PreparedStatement prest = con.prepareStatement(sql); BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter movie name:"); String mov = bf.readLine(); prest.setString(1, mov); System.out.println("Enter releases year of movie:"); int year = Integer.parseInt(bf.readLine()); prest.setInt(2, year); int count = prest.executeUpdate(); System.out.println(count + "row(s) affected"); con.close(); } catch (SQLException s){ System.out.println("SQL statement is not executed!"); } } catch (Exception e){ e.printStackTrace(); } } }
16. Update en JDBC import java.sql.*; public class UpdatesRecords{ public static void main(String[] args) { System.out.println("Updates Records Example through Prepared Statement!"); Connection con = null; try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/jdbctutorial","root","root"); try{ String sql = " UPDATE movies SET title = ? WHERE year_made = ?"; PreparedStatement prest = con.prepareStatement(sql); prest.setString(1,"Sanam We wafafa"); prest.setInt(2,2005); prest.executeUpdate(); System.out.println("Updating Successfully!"); con.close(); } catch (SQLException s){ System.out.println("SQL statement is not executed!"); } } catch (Exception e){ e.printStackTrace(); } } }
17. Select en JDBC import java.sql.*; public class SelectRecords{ public static void main(String[] args) { System.out.println("Select Records Example by using the Prepared Statement!"); Connection con = null; int count = 0; try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/jdbctutorial","root","root"); try{ String sql = " SELECT title,year_made FROM movies WHERE year_made >= ? AND year_made <= ? "; PreparedStatement prest = con.prepareStatement(sql); prest.setInt(1,1980); prest.setInt(2,2004); ResultSet rs = prest.executeQuery(); while (rs.next()){ String mov_name = rs.getString(1); int mov_year = rs.getInt(2); count++; System.out.println(mov_name + "" + "- " + mov_year); } System.out.println("Number of records: " + count); prest.close(); con.close(); } catch (SQLException s){ System.out.println("SQL statement is not executed!"); } } catch (Exception e){ e.printStackTrace(); } } }