Programming In Java | Week 11
Programming In Java | Week 11
Course Link: https://onlinecourses.nptel.ac.in/noc23_cs74/course
Programming Assignment
1. Complete the code segment to insert the following data using prepared statement in the existing table ‘PLAYERS’.
Column | UID | First_Name | Last_Name | Age |
Row 1 | 1 | Ram | Gopal | 26 |
Row 2 | 2 | John | Mayer | 22 |
Solution:
String query= "insert into PLAYERS(UID,first_name,last_name,age)" + "values (?, ?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt (1, 1);
preparedStmt.setString (2, "Ram");
preparedStmt.setString (3, "Gopal");
preparedStmt.setInt(4, 26);
preparedStmt.execute();
PreparedStatement preparedStmt2 = conn.prepareStatement(query);
preparedStmt2.setInt (1, 2);
preparedStmt2.setString (2, "John");
preparedStmt2.setString (3, "Mayer");
preparedStmt2.setInt(4, 22);
preparedStmt2.execute();
2. Write the required code in order to update the following data in the table ‘PLAYERS’.
Column | UID | First_Name | Last_Name | Age |
From | 1 | Ram | Gopal | 26 |
To | 1 | Rama | Gopala | 24 |
Solution:
query="UPDATE Players SET First_name='Rama',Last_name='Gopala',Age=24 WHERE UID=1;";
stmt.executeUpdate(query);
3. Write the appropriate code in order to delete the following data in the table ‘PLAYERS’.
Column | UID | First_Name | Last_Name | Age |
Delete | 1 | Rama | Gopala | 24 |
Solution:
stmt.executeUpdate("DELETE FROM Players WHERE UID = 1;");
4. Complete the following program to calculate the average age of the players in the table ‘PLAYERS’.
Structure of Table ‘PLAYERS’ is given below:
Column | UID | First_Name | Last_Name | Age |
Type | Integer | Varchar (45) | Varchar (45) | Integer |
Solution:
ResultSet rs = stmt.executeQuery("SELECT * FROM players;");
int count=0,total=0;
while(rs.next()){
count++;
total = total + Integer.parseInt(rs.getString(4));
}
System.out.println("Average age of players is " +(total/count));
conn.close();
5. Complete the code segment to drop the table named ‘PLAYERS’.
Solution:
query = "DROP TABLE players;";
stmt.executeUpdate(query);