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’.

ColumnUIDFirst_NameLast_NameAge
Row 11RamGopal26
Row 22JohnMayer22

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’.

ColumnUIDFirst_NameLast_NameAge
From1RamGopal26
To1RamaGopala24

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’.

ColumnUIDFirst_NameLast_NameAge
Delete1RamaGopala24

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:

ColumnUIDFirst_NameLast_NameAge
TypeIntegerVarchar (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);

* The material and content uploaded on this website are for general information and reference purposes only !

Please do it by your own first!
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments



0
Would love your thoughts, please comment.x
()
x