Programming In Java | Week 10
Programming In Java | Week 10
Course Link: https://onlinecourses.nptel.ac.in/noc23_cs74/course
Programming Assignment
1. The following code needs some package to work properly. Write appropriate code to import the required package(s) in order to make the program compile and execute successfully.
Solution:
import java.sql.*;
import java.lang.*;
2. Write the JDBC codes needed to create a Connection interface using the DriverManager class and the variable DB_URL. Check whether the connection is successful using ‘isAlive(timeout)’ method to generate the output, which is either ‘true’ or ‘false’.
Note the following points carefully:
1. Name the connection object as ‘conn’ only.
2. Use timeout value as 1.
Solution:
conn = DriverManager.getConnection(DB_URL);
boolean isAlive = conn.isWrapperFor(java.sql.Connection.class)
&& conn.unwrap(java.sql.Connection.class).isValid(1);
if (isAlive)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
conn.close();
3. Due to some mistakes in the below code, the code is not compiled/executable. Modify and debug the JDBC code to make it execute successfully.
Solution:
import java.sql.*;
import java.lang.*;
import java.util.Scanner;
public class Question103 {
public static void main(String args[]) {
try {
Connection conn = null;
Statement stmt = null;
String DB_URL = "jdbc:sqlite:/tempfs/db";
System.setProperty("org.sqlite.tmpdir", "/tempfs");
conn = DriverManager.getConnection(DB_URL);
conn.close();
System.out.print(conn.isClosed());
}
catch(Exception e){ System.out.println(e);}
}
}
4. Complete the code segment to create a new table named ‘PLAYERS’ in SQL database using the following information.
Column | UID | First_Name | Last_Name | Age |
Type | Integer | Varchar (45) | Varchar (45) | Integer |
Solution:
String CREATE_TABLE_SQL="CREATE TABLE players (UID INT, First_Name VARCHAR(45), Last_Name VARCHAR(45), Age INT);";
stmt.executeUpdate(CREATE_TABLE_SQL);
5. Complete the code segment to rename an already created table named ‘PLAYERS’ into ‘SPORTS’.
Solution:
String alter="ALTER TABLE players RENAME TO sports;";
stmt.executeUpdate(alter);