• Loading Driver
• Establishing Connection
• Executing Statements
• Getting Results
• Closing Database Connection
Before explaining you the JDBC Steps for making connection to the database and retrieving the employee from the tables, we will provide you the structure of the database and sample data.
Table structure for table `employee`
CREATE TABLE `employee` ( `employee_name` varchar(50) NOT NULL, PRIMARY KEY (`employee_name`) );
INSERT INTO `employee` (`employee_name`) VALUES
('Deepak Kumar'),
('Harish Joshi'),
('Rinku roy'),
('Vinod Kumar');
Data inserting in MySQL database table:
mysql> insert into employee values('Deepak Kumar');
mysql> insert into employee values('Harish Joshi');
mysql> insert into employee values('Harish Joshi');
mysql> insert into employee values('Rinku roy');
mysql> insert into employee values('Vinod Kumar');
mysql> select *from employee;
employee_name
Deepak Kumar
Harish Joshi
Rinku roy
Vinod Kumar
Here is the code of java program that retrieves all the employee data from database and displays on the console:
/*Import JDBC core packages.
Following statement imports the java.sql package, which contains the JDBC core API. */
import java.sql.*;
public class RetriveAllEmployees{
public static void main(String[] args) {
System.out.println("Getting All Rows from employee table!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "jdbc";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, user, pass);
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employee");
System.out.println("Employee Name: " );
while (res.next()) {
String employeeName = res.getString("employee_name");
System.out.println(employeeName );
}
con.close();
}
catch (ClassNotFoundException e){
System.err.println("Could not load JDBC driver");
System.out.println("Exception: " + e);
e.printStackTrace();
}
catch(SQLException ex){
System.err.println("SQLException information");
while(ex!=null) {
System.err.println ("Error msg: " + ex.getMessage());
System.err.println ("SQLSTATE: " + ex.getSQLState());
System.err.println ("Error code: " + ex.getErrorCode());
ex.printStackTrace();
ex = ex.getNextException(); // For drivers that support chained exceptions
}
}
}}
No comments:
Post a Comment