Professional Documents
Culture Documents
dept_name varchar(50)
location varchar(50)
Employee Table:
emp_name varchar(50)
dob date
salary double
01
02 import java.io.BufferedReader;
03 import java.io.IOException;
04 import java.io.InputStreamReader;
05 import java.sql.Connection;
06 import java.sql.ResultSet;
07 import java.sql.SQLException;
08 import java.sql.Statement;
09 import com.theopentutorials.jdbc.db.DbUtil;
10 import com.theopentutorials.jdbc.db.JDBCMySQLConnection;
11 import com.theopentutorials.jdbc.to.Employee;
12
13 public class JDBCMySQLDemo {
14 public static void main(String[] args) {
15 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
16 System.out.println("Enter the EmployeeID:");
17
18 int employeeId;
19 try {
20 employeeId = Integer.parseInt(br.readLine());
21 JDBCMySQLDemo demo = new JDBCMySQLDemo();
22 Employee employee = demo.getEmployee(employeeId);
23 System.out.println(employee);
24 } catch (NumberFormatException e) {
25 e.printStackTrace();
26 } catch (IOException e) {
27 e.printStackTrace();
28 }
29 }
30
31 public Employee getEmployee(int employeeId) {
32 ResultSet rs = null;
33 Connection connection = null;
34 Statement statement = null;
35
36 Employee employee = null;
37 String query = "SELECT * FROM employee WHERE emp_id=" + employeeId;
38 try {
39 connection = JDBCMySQLConnection.getConnection();
40 statement = connection.createStatement();
41 rs = statement.executeQuery(query);
42
43 if (rs.next()) {
44 employee = new Employee();
45 employee.setEmpId(rs.getInt("emp_id"));
46 employee.setEmpName(rs.getString("emp_name"));
47 employee.setDob(rs.getDate("dob"));
48 employee.setSalary(rs.getDouble("salary"));
49 employee.setDeptId((rs.getInt("dept_id")));
50 }
51 } catch (SQLException e) {
52 e.printStackTrace();
53 } finally {
54 if (connection != null) {
55 try {
56 connection.close();
57 } catch (SQLException e) {
58 e.printStackTrace();
59 }
60 }
61 }
62 return employee;
63 }
64 }
65
This JDBC MySQL example gets an employee ID from user, finds this employee in database and prints
the details to standard output.