Вы находитесь на странице: 1из 7

5 AIM Implement Employee information system using JDBC.

Download and install MySQL database


This MySQL JDBC example requires MySQL database to be installed.
 This Java database application uses MySQL as sample database.
Java MySQL Connector
JDBC API mostly consists of interfaces which work independently of any database. A database specific
driver is required for each database which implements the JDBC API.
The JDBC database Connector provides access to the database. To reach the database using JDBC we
need a JDBC driver from the database provider in our case – MySQL. This connector is typically delivered
with the product in a jar or zip file or available in the provider’s website. These files must be in our
classpath (which is explained later under Configure JDBC Driver in Eclipse) otherwise we will get some
class-not-found-exceptions indicating that the driver was not found on the classpath.
 MySQL Connector/J is the official MySQL JDBC driver.
 The Java MySQL connector JAR can be downloaded
from: http://dev.mysql.com/downloads/connector/j/. This tutorial uses JDBC MySQL connector
5.1 version. Unzip the connector to a safe location on your computer which contains MySQL
Connector/J JAR.

JDBC MySQL Sample Database


This JDBC MySQL example uses a sample database “jdbcdb” which contains the following table;
 Create a database in MySQL and name it as “jdbcdb“.
 Create the following tables inside this database.
Department Table:
Field Type Key Extra

dept_id int Primary Key auto_increment

dept_name varchar(50)

location varchar(50)

Employee Table:

Field Type Key Extra

emp_id int Primary Key auto_increment

emp_name varchar(50)

dob date

salary double

Foreign key references


dept_id int
department(dept_id)

Create a Java project in Eclipse IDE


 Open Eclipse IDE.
 Create a new Java Project and name it as “JDBCMySQLSample“. If you are a newbie, refer this
link on getting started with Java and Eclipse.
JDBC MySQL Connection String URL
We write a class (JDBCMySQLConnection) defining database connection configuration statements and
methods to make JDBC connect to MySQL database.
Following steps are involved in JDBC MySQL connection.
Use Interfaces from java.sql package
You need to import required classes/interfaces from java.sql.* package which acts as a bridge between
Java application and database.
Load MySQL Java driver
The Java MySQL driver (com.mysql.jdbc.Driver) is available in the downloaded Java MySQL Connector
JAR file. This connector JAR file needs to be included in the client project’s classpath which is explained
later under Configure JDBC Driver in Eclipse.
The statement Class.forName (“com.mysql.jdbc.driver”) loads the MySQL Java driver class in memory.
In the below code, we have created a static final String variable (constant) and passing it as parameter to
class.forName as shown below.
1 public static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
2 ...
3 Class.forName(DRIVER_CLASS);
Establish Java MySQL connection
We connect to MySQL from Java using DriverManager class by
calling DriverManager.getConnection()method. This method requires a JDBC MySQL connection URL
string, MySQL database username and password. In this example, we have created these as constant
variables and passed it in getConnection() method.
1 public static final String URL = "jdbc:mysql://localhost/jdbcdb";
2 public static final String USER = "YOUR_DATABASE_USERNAME";
3 public static final String PASSWORD = "YOUR_DATABASE_PASSWORD";
4 ...
5 ...
6 Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
Java database connection string URL:
jdbc:<DBMS>://<HOSTNAME>:<PORT_NUMBER>/YOUR_DATABASE_NAME
Example, for Java MySQL connection string URL:
jdbc:mysql://localhost:3306/jdbcdb
where,
 “jdbc:” – Required for all databases
 “mysql” – Any Relational Database. In this case, it is mysql
 localhost - is the name of the server hosting your database
 3306 is the default port number for MySQL, which can be omitted if not changed to any other
number.
 YOUR_DATABASE_NAME is the MySQL database name, in this example it is “jdbcdb”
To complete the above steps, create a new class JDBCMySQLConnection in
package com.theopentutorials.jdbc.db and copy the following code.
01
02 //Step 1: Use interfaces from java.sql package
03 import java.sql.Connection;
04 import java.sql.DriverManager;
05 import java.sql.SQLException;
06
07 public class JDBCMySQLConnection {
08 //static reference to itself
09 private static JDBCMySQLConnection instance = new JDBCMySQLConnection();
10 public static final String URL = "jdbc:mysql://localhost/jdbcdb";
11 public static final String USER = "YOUR_DATABASE_USERNAME";
12 public static final String PASSWORD = "YOUR_DATABASE_PASSWORD";
13 public static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
14
15 //private constructor
16 private JDBCMySQLConnection() {
17 try {
18 //Step 2: Load MySQL Java driver
19 Class.forName(DRIVER_CLASS);
20 } catch (ClassNotFoundException e) {
21 e.printStackTrace();
22 }
23 }
24
25 private Connection createConnection() {
26
27 Connection connection = null;
28 try {
29 //Step 3: Establish Java MySQL connection
30 connection = DriverManager.getConnection(URL, USER, PASSWORD);
31 } catch (SQLException e) {
32 System.out.println("ERROR: Unable to Connect to Database.");
33 }
34 return connection;
35 }
36
37 public static Connection getConnection() {
38 return instance.createConnection();
39 }
40 }
41
Employee class:
We write a class with properties defining the table attributes. For example, to query the employee table
and retrieve employee details, we write a class with following code;
01 package com.theopentutorials.jdbc.to;
02
03 import java.util.Date;
04
05 public class Employee {
06
07 private int empId;
08 private String empName;
09 private Date dob;
10 private double salary;
11 private int deptId;
12
13 public int getEmpId() {
14 return empId;
15 }
16 public void setEmpId(int empId) {
17 this.empId = empId;
18 }
19 public String getEmpName() {
20 return empName;
21 }
22 public void setEmpName(String empName) {
23 this.empName = empName;
24 }
25 public Date getDob() {
26 return dob;
27 }
28 public void setDob(Date dob) {
29 this.dob = dob;
30 }
31 public double getSalary() {
32 return salary;
33 }
34 public void setSalary(double salary) {
35 this.salary = salary;
36 }
37 public void setDeptId(int deptId) {
38 this.deptId = deptId;
39 }
40 public int getDeptId() {
41 return deptId;
42 }
43
44 //toString()
45 @Override
46 public String toString() {
47 return "Employee [empId=" + empId + ", empName=" + empName + ", dob="
48 + dob + ", salary=" + salary + ", deptId=" + deptId + "]";
49 }
50 }
Java Application Client (main())
 An application involving Java with database to process any SQL statement must follow these
steps:
o Establish a connection. (This is done by JDBCMySQLConnection class mentioned above)
o Create a Statement object. (Line 41)
o Execute the query. (Line 42)
o Process the ResultSet object. This is required only for SELECT SQL query. (Line 44-51)
o Close the connection. (Line 57)

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.

Вам также может понравиться