Untitled
unknown
java
10 months ago
2.9 kB
3
Indexable
package com.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Scanner; public class TEST1 { public static void main(String[] args) { String dbURL = "jdbc:oracle:thin:@localhost:1521:xe"; // Example SID String username = "your_username"; // Replace with your DB username String password = "your_password"; // Replace with your DB password try { Class.forName("oracle.jdbc.OracleDriver"); Connection connection = DriverManager.getConnection(dbURL, username, password); System.out.println("Connected to the database successfully!"); // Insert a new record into the Employee123 table String insertQuery = "INSERT INTO Employee123 (e_id, e_name, e_salary) VALUES (?, ?, ?)"; PreparedStatement insertStatement = connection.prepareStatement(insertQuery); // Sample data for insertion int newId = 1; // Ensure this ID is unique String newName = "John Doe"; int newSalary = 50000; insertStatement.setInt(1, newId); insertStatement.setString(2, newName); insertStatement.setInt(3, newSalary); int rowsInserted = insertStatement.executeUpdate(); if (rowsInserted > 0) { System.out.println("A new employee was inserted successfully!"); } // Close the insert statement insertStatement.close(); // Now proceed with the select operation String selectQuery = "SELECT * FROM Employee123 WHERE e_salary = ?"; Scanner sc = new Scanner(System.in); System.out.print("Enter the salary to search: "); int s1 = sc.nextInt(); sc.close(); System.out.println("Executing query: " + selectQuery); System.out.println("With salary value: " + s1); PreparedStatement preparedStatement = connection.prepareStatement(selectQuery); preparedStatement.setInt(1, s1); ResultSet resultSet = preparedStatement.executeQuery(); if (!resultSet.isBeforeFirst()) { System.out.println("No record found"); } else { while (resultSet.next()) { int id = resultSet.getInt("e_id"); String name = resultSet.getString("e_name"); System.out.println("ID: " + id + ", Name: " + name); } } resultSet.close(); preparedStatement.close(); connection.close(); } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); } } }
Editor is loading...
Leave a Comment