writing java program for database update query

Solutions on MaxInterview for writing java program for database update query by the best coders in the world

showing results for - "writing java program for database update query"
Diego
04 Oct 2018
1//STEP 1. Import required packages
2import java.sql.*;
3
4public class JDBCExample {
5   // JDBC driver name and database URL
6   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
7   static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
8
9   //  Database credentials
10   static final String USER = "username";
11   static final String PASS = "password";
12   
13   public static void main(String[] args) {
14   Connection conn = null;
15   Statement stmt = null;
16   try{
17      //STEP 2: Register JDBC driver
18      Class.forName("com.mysql.jdbc.Driver");
19
20      //STEP 3: Open a connection
21      System.out.println("Connecting to a selected database...");
22      conn = DriverManager.getConnection(DB_URL, USER, PASS);
23      System.out.println("Connected database successfully...");
24      
25      //STEP 4: Execute a query
26      System.out.println("Creating statement...");
27      stmt = conn.createStatement();
28      String sql = "UPDATE Registration " +
29                   "SET age = 30 WHERE id in (100, 101)";
30      stmt.executeUpdate(sql);
31
32      // Now you can extract all the records
33      // to see the updated records
34      sql = "SELECT id, first, last, age FROM Registration";
35      ResultSet rs = stmt.executeQuery(sql);
36
37      while(rs.next()){
38         //Retrieve by column name
39         int id  = rs.getInt("id");
40         int age = rs.getInt("age");
41         String first = rs.getString("first");
42         String last = rs.getString("last");
43
44         //Display values
45         System.out.print("ID: " + id);
46         System.out.print(", Age: " + age);
47         System.out.print(", First: " + first);
48         System.out.println(", Last: " + last);
49      }
50      rs.close();
51   }catch(SQLException se){
52      //Handle errors for JDBC
53      se.printStackTrace();
54   }catch(Exception e){
55      //Handle errors for Class.forName
56      e.printStackTrace();
57   }finally{
58      //finally block used to close resources
59      try{
60         if(stmt!=null)
61            conn.close();
62      }catch(SQLException se){
63      }// do nothing
64      try{
65         if(conn!=null)
66            conn.close();
67      }catch(SQLException se){
68         se.printStackTrace();
69      }//end finally try
70   }//end try
71   System.out.println("Goodbye!");
72}//end main
73}//end JDBCExample