0% found this document useful (0 votes)
4 views

technical training coding

The document contains Java code examples for various SQL operations using JDBC, including sorting employee salaries, filtering records based on address and name, checking balanced parentheses, and implementing applications for expense tracking, banking, employee management, and library management. Each section includes a brief explanation of the code's functionality and the significance of specific SQL statements and Java packages used. Additionally, it addresses common questions and answers (Viva) related to the code's logic and database interactions.

Uploaded by

22eg105a63
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

technical training coding

The document contains Java code examples for various SQL operations using JDBC, including sorting employee salaries, filtering records based on address and name, checking balanced parentheses, and implementing applications for expense tracking, banking, employee management, and library management. Each section includes a brief explanation of the code's functionality and the significance of specific SQL statements and Java packages used. Additionally, it addresses common questions and answers (Viva) related to the code's logic and database interactions.

Uploaded by

22eg105a63
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

java

Copy code
// Q1: Select all rows from a table based on sorting order of salaries
import java.sql.*;

public class SortSalaries {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";

try (Connection conn = DriverManager.getConnection(url, user, password)) {


String query = "SELECT * FROM employees ORDER BY salary DESC";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name") + " " +
rs.getDouble("salary"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
java
Copy code
// Q2: Select range of records based on address
import java.sql.*;

public class AddressRange {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";

try (Connection conn = DriverManager.getConnection(url, user, password)) {


String query = "SELECT * FROM employees WHERE address LIKE 'New York%'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name") + " " +
rs.getString("address"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
java
Copy code
// Q3: Select range of records based on initial characters of the employee name
import java.sql.*;

public class NameFilter {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";

try (Connection conn = DriverManager.getConnection(url, user, password)) {


String query = "SELECT * FROM employees WHERE name LIKE 'A%'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name") + " " +
rs.getString("address"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
java
Copy code
// Q4: Check if a string of parentheses is balanced
import java.util.Stack;

public class BalancedParentheses {


public static boolean isBalanced(String s) {
Stack<Character> stack = new Stack<>();
for (char ch : s.toCharArray()) {
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
} else {
if (stack.isEmpty()) return false;
char top = stack.pop();
if ((ch == ')' && top != '(') || (ch == '}' && top != '{') || (ch ==
']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
}

public static void main(String[] args) {


String[] inputs = {"{}()", "({()})", "{}(", "[]"};
for (String s : inputs) {
System.out.println(isBalanced(s));
}
}
}
java
Copy code
// Q5: JDBC Application for Expense Tracker
import java.sql.*;
import java.util.Scanner;

public class ExpenseTracker {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";

try (Connection conn = DriverManager.getConnection(url, user, password);


Scanner sc = new Scanner(System.in)) {

System.out.println("1. Add Expense\n2. View Report\n3. Exit");


int choice = sc.nextInt();

if (choice == 1) {
System.out.print("Enter user ID: ");
int userId = sc.nextInt();
System.out.print("Enter amount: ");
double amount = sc.nextDouble();
System.out.print("Enter category: ");
String category = sc.next();
System.out.print("Enter date (YYYY-MM-DD): ");
String date = sc.next();
String query = "INSERT INTO expenses (user_id, amount, category, date)
VALUES (?, ?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, userId);
ps.setDouble(2, amount);
ps.setString(3, category);
ps.setDate(4, Date.valueOf(date));
ps.executeUpdate();
System.out.println("Expense added!");
} else if (choice == 2) {
System.out.print("Enter category: ");
String category = sc.next();

String query = "SELECT * FROM expenses WHERE category = ?";


PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, category);
ResultSet rs = ps.executeQuery();

while (rs.next()) {
System.out.println(rs.getInt("expense_id") + " " +
rs.getDouble("amount") + " " + rs.getString("date"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
java
Copy code
// Q6: JDBC Application for Banking System
import java.sql.*;
import java.util.Scanner;

public class BankingSystem {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";

try (Connection conn = DriverManager.getConnection(url, user, password);


Scanner sc = new Scanner(System.in)) {

System.out.println("1. Create Account\n2. Deposit\n3. Withdraw\n4.


Transaction History");
int choice = sc.nextInt();

if (choice == 1) {
System.out.print("Enter name: ");
String name = sc.next();
System.out.print("Enter initial balance: ");
double balance = sc.nextDouble();

String query = "INSERT INTO accounts (user_name, balance) VALUES


(?, ?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, name);
ps.setDouble(2, balance);
ps.executeUpdate();
System.out.println("Account created!");
} else if (choice == 2 || choice == 3) {
System.out.print("Enter account ID: ");
int accountId = sc.nextInt();
System.out.print("Enter amount: ");
double amount = sc.nextDouble();

String transactionType = choice == 2 ? "Deposit" : "Withdraw";


String query = "INSERT INTO transactions (account_id, type, amount)
VALUES (?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, accountId);
ps.setString(2, transactionType);
ps.setDouble(3, amount);
ps.executeUpdate();

String updateBalance = choice == 2


? "UPDATE accounts SET balance = balance + ? WHERE account_id =
?"
: "UPDATE accounts SET balance = balance - ? WHERE account_id =
?";
PreparedStatement ps2 = conn.prepareStatement(updateBalance);
ps2.setDouble(1, amount);
ps2.setInt(2, accountId);
ps2.executeUpdate();
System.out.println(transactionType + " successful!");
} else if (choice == 4) {
System.out.print("Enter account ID: ");
int accountId = sc.nextInt();

String query = "SELECT * FROM transactions WHERE account_id = ?";


PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, accountId);
ResultSet rs = ps.executeQuery();

while (rs.next()) {
System.out.println(rs.getInt("transaction_id") + " " +
rs.getString("type") + " " + rs.getDouble("amount"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
java
Copy code
// Q7: JDBC Application for Employee Management System
import java.sql.*;
import java.util.Scanner;

public class EmployeeManagement {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";

try (Connection conn = DriverManager.getConnection(url, user, password);


Scanner sc = new Scanner(System.in)) {

System.out.println("1. Add Employee\n2. Edit Employee\n3. Delete Employee\


n4. View Employees");
int choice = sc.nextInt();

if (choice == 1) {
System.out.print("Enter name: ");
String name = sc.next();
System.out.print("Enter email: ");
String email = sc.next();
System.out.print("Enter department ID: ");
int departmentId = sc.nextInt();
System.out.print("Enter salary: ");
double salary = sc.nextDouble();
String query = "INSERT INTO employees (name, email, department_id,
salary) VALUES (?, ?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, name);
ps.setString(2, email);
ps.setInt(3, departmentId);
ps.setDouble(4, salary);
ps.executeUpdate();
System.out.println("Employee added!");
} else if (choice == 4) {
String query = "SELECT * FROM employees";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {
System.out.println(rs.getInt("employee_id") + " " +
rs.getString("name") + " " + rs.getDouble("salary"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
java
Copy code
// Q8: JDBC Application for Library Management System
import java.sql.*;
import java.util.Scanner;

public class LibraryManagement {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";

try (Connection conn = DriverManager.getConnection(url, user, password);


Scanner sc = new Scanner(System.in)) {

System.out.println("1. Add Book\n2. Update Book\n3. Delete Book\n4. View


Books");
int choice = sc.nextInt();

if (choice == 1) {
System.out.print("Enter title: ");
String title = sc.next();
System.out.print("Enter author: ");
String author = sc.next();
System.out.print("Enter publisher: ");
String publisher = sc.next();
System.out.print("Enter quantity: ");
int quantity = sc.nextInt();

String query = "INSERT INTO books (title, author, publisher, quantity)


VALUES (?, ?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, title);
ps.setString(2, author);
ps.setString(3, publisher);
ps.setInt(4, quantity);
ps.executeUpdate();
System.out.println("Book added!");
} else if (choice == 4) {
String query = "SELECT * FROM books";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getInt("book_id") + " " +
rs.getString("title") + " " + rs.getInt("quantity"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}Q1: Select all rows from a table based on sorting order of salaries

Viva:

1. What is the purpose of ORDER BY in this query?


o It is used to sort the results of the query, in this case, in descending order of salaries.
2. Why use Statement instead of PreparedStatement?
o Statement is used when there are no user inputs that require binding. In this case, the query
doesn’t depend on external user inputs, so Statement is suitable.

Explanation:

 Packages used:
o java.sql.*: This package provides the JDBC API for database connectivity, including
Connection, Statement, and ResultSet.
 Statements used:
o Statement stmt = conn.createStatement();: Creates a Statement object to execute
SQL queries.
o stmt.executeQuery(query);: Executes the query to retrieve the data from the database.

Q2: Select range of records based on address

Viva:

1. What is the significance of the LIKE clause?


o LIKE is used for pattern matching. The query is filtering records where the address starts with
'New York'.
2. Why don't you need to use PreparedStatement here?
o In this case, no user input is being directly incorporated into the query, hence Statement
works fine.

Explanation:

 Packages used:
o java.sql.*: For JDBC classes like Connection, Statement, ResultSet.
 Statements used:
o SELECT * FROM employees WHERE address LIKE 'New York%': SQL query to filter
employees with addresses starting with 'New York'.

Q3: Select range of records based on initial characters of the employee name

Viva:
1. What is the purpose of % in the query?
o The % acts as a wildcard in SQL, meaning it can match any characters after the letter 'A'. This
helps in filtering employees whose name begins with 'A'.
2. How does executeQuery() method work in the program?
o executeQuery() is used to execute SQL SELECT statements and returns a ResultSet
object containing the result of the query.

Explanation:

 Packages used:
o java.sql.*: For database connection, creating statement, and processing results.
 Statements used:
o stmt.executeQuery(query);: Executes the SQL query to retrieve the data.

Q4: Check if a string of parentheses is balanced

Viva:

1. Why do we use a stack to solve this problem?


o A stack is ideal for this problem because it follows a Last-In-First-Out (LIFO) order, which
fits well for matching opening and closing parentheses.
2. Explain the process flow inside the isBalanced() method.
o The method pushes opening parentheses onto the stack. When it encounters closing
parentheses, it pops the stack and checks for matching pairs.

Explanation:

 Packages used:
o java.util.Stack: For using the stack data structure to store characters.
 Statements used:
o stack.push(ch);: Pushes a character onto the stack.
o stack.pop();: Removes the top character from the stack.
o The checks inside if ensure that the parentheses match.

Q5: JDBC Application for Expense Tracker

Viva:

1. How is data insertion done in this example?


o Data is inserted using the PreparedStatement to insert expense details into the expenses
table.
2. What is the role of PreparedStatement here?
o It helps in securely adding data by preventing SQL injection attacks and binding parameters
to the SQL query.

Explanation:

 Packages used:
o java.sql.*: For database connection, prepared statement, result set processing.
o java.util.Scanner: For reading user input.
 Statements used:
o ps.setInt(), ps.setDouble(), ps.setString(): These are used to bind the user's input to
the placeholders in the query.
o ps.executeUpdate();: Executes the update query (like insertion).

Q6: JDBC Application for Banking System

Viva:

1. Explain how the account balance is updated after a deposit or withdrawal.


o After each transaction, the account balance is updated by adding or subtracting the
transaction amount, using an UPDATE query.
2. Why do you use PreparedStatement for user input?
o To prevent SQL injection by binding variables to the query rather than concatenating user
inputs directly into the SQL query.

Explanation:

 Packages used:
o java.sql.*: For database connections and performing queries.
o java.util.Scanner: To read user inputs.
 Statements used:
o PreparedStatement ps = conn.prepareStatement(query);: Prepares the SQL query for
secure execution.
o ps.executeUpdate();: Executes insertion or update commands in the database.

Q7: JDBC Application for Employee Management System

Viva:

1. Explain how the insertion of an employee is handled.


o The employee details (like name, email, salary) are inserted using a PreparedStatement,
with parameters bound to prevent SQL injection.
2. What does the ResultSet contain in this scenario?
o The ResultSet will contain the data returned by the SELECT query, in this case, a list of
employees.

Explanation:

 Packages used:
o java.sql.*: Includes classes for connecting to the database and managing queries like
Statement and ResultSet.
 Statements used:
o ps.setString(), ps.setInt(), ps.setDouble(): Binding user input into the query using
PreparedStatement.
o stmt.executeQuery(query);: Executes the SQL query to retrieve the employee list.

Q8: JDBC Application for Library Management System


Viva:

1. What is the purpose of using PreparedStatement?


o It allows for safe parameterized queries, protecting against SQL injection by binding user
inputs to query parameters.
2. How is the retrieval of book details managed?
o A SELECT query is executed, and the resulting ResultSet is processed to retrieve each
book’s details.

Explanation:

 Packages used:
o java.sql.*: Includes essential JDBC classes like Connection, Statement, and ResultSet.
 Statements used:
o PreparedStatement: Used to safely insert book data into the database.
o stmt.executeQuery(): Executes the query and retrieves a list of all books.

These explanations cover the core concepts, packages, and statements used in each example, focusing on
JDBC operations for database handling, user input management, and SQL execution in Java applications.

You might also like