ja16
- Write a java program to create a TreeSet, add some colors (String) and print out the
content of TreeSet in ascending order. [15 M]
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<String> colors = new TreeSet<>();
colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.add("Yellow");
colors.add("Orange");
System.out.println("Colors in ascending order:");
for (String color : colors) {
System.out.println(color);
}
}
}
- Write a Java program to accept the details of Teacher (TNo, TName, Subject). Insert at
least 5 Records into Teacher Table and display the details of Teacher who is teaching
“JAVA” Subject. (Use PreparedStatement Interface)
import java.sql.*;
public class TeacherDetails {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// Establishing connection
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name", "username", "password");
// SQL query to insert teacher records
String insertQuery = "INSERT INTO Teacher (TNo, TName, Subject) VALUES (?, ?, ?)";
// Preparing statement
preparedStatement = connection.prepareStatement(insertQuery);
// Inserting teacher records
for (int i = 1; i <= 5; i++) {
preparedStatement.setInt(1, i);
preparedStatement.setString(2, "Teacher " + i);
preparedStatement.setString(3, "JAVA");
preparedStatement.executeUpdate();
}
// SQL query to select teachers teaching "JAVA" subject
String selectQuery = "SELECT * FROM Teacher WHERE Subject = ?";
// Preparing statement
preparedStatement = connection.prepareStatement(selectQuery);
preparedStatement.setString(1, "JAVA");
// Executing query
resultSet = preparedStatement.executeQuery();
// Displaying details of teachers teaching "JAVA" subject
System.out.println("Details of teachers teaching JAVA subject:");
while (resultSet.next()) {
System.out.println("Teacher Number: " + resultSet.getInt("TNo"));
System.out.println("Teacher Name: " + resultSet.getString("TName"));
System.out.println("Subject: " + resultSet.getString("Subject"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Closing resources
try {
if (resultSet != null) resultSet.close();
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}