Hackerss.com

Hackerss.com is a community of amazing hackers

Hackerss is a community for developers, data scientitst, ethical hackers, hardware enthusiasts or any person that want to learn / share their knowledge of any aspect of digital technology.

Create account Log in
hackerss
hackerss

Posted on

Java Connect to an oracle database and retrieve all info of a table


import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OracleJDBC {

    public static void main(String[] args) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("select * from employees");
            List<Employee> employees = new ArrayList<>();
            while (rs.next()) {
                Employee employee = new Employee();
                employee.setId(rs.getInt("id"));
                employee.setName(rs.getString("name"));
                employee.setSalary(rs.getInt("salary"));
                employees.add(employee);
            }
            for (Employee employee : employees) {
                System.out.println(employee);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static class Employee {

        private int id;
        private String name;
        private int salary;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getSalary() {
            return salary;
        }

        public void setSalary(int salary) {
            this.salary = salary;
        }

        @Override
        public String toString() {
            return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", salary=" + salary + '}';
        }

    }

}
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)