Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
 
 
Search All Tutorials

 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 
JDBC
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

JDBC Steps – Basic steps in writing a JDBC Application

                         

This section gives you brief description of JDBC Steps for making connection with the database, executing the query and showing the data to the user. In this application we have connected to the MySQL database and retrieved the employee names from the database. Here are the JDBC Steps to be followed while writing JDBC program:

  • 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.

Here is the sql script to create table and populate the table with 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');
Query OK, 1 row affected (0.24 sec)

mysql> insert into employee values('Harish Joshi');
Query OK, 1 row affected (0.05 sec)

mysql> insert into employee values('Harish Joshi');
ERROR 1062 (23000): Duplicate entry 'Harish Joshi' for key 1
mysql> insert into employee values('Rinku roy');
Query OK, 1 row affected (0.03 sec)

mysql> insert into employee values('Vinod Kumar');
Query OK, 1 row affected (0.04 sec)

mysql> select *from employee;
+---------------+
| employee_name |
+---------------+
| Deepak Kumar |
| Harish Joshi |
| Rinku roy |
| Vinod Kumar |
+---------------+
4 rows in set (0.04 sec)

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
      }
    }
  }
}

Explanation of JDBC Steps:

  • Loading Driver
    Loading Database driver is very first step towards making JDBC connectivity with the database. It is necessary to load the JDBC drivers before attempting to connect to the database.
    The JDBC drivers automatically register themselves with the JDBC system when loaded. Here is the code for loading the JDBC driver:
    Class.forName(driver).newInstance();
       
  • Establishing Connection
    In the above step we have loaded the database driver to be used. Now its time to make the connection with the database server. In the Establishing Connection step we will logon to the database with user name and password. Following code we have used to make the connection with the database:
    con = DriverManager.getConnection(url+db, user, pass);
       
  • Executing Statements
    In the previous step we established the connection with the database, now its time to execute query against database. You can run any type of query against database to perform database operations. In this example we will select all the rows from employee table. Here is the code that actually execute the statements against database:
    ResultSet res = st.executeQuery( "SELECT * FROM  employee" );
       
  • Getting Results
    In this step we receives the result of execute statement. In this case we will fetch the employees records from the recordset object and show on the console. Here is the code:
             while  (res.next()) {
               String employeeName  = res.getInt( " employee_name " );
               System.out.println( employeeName  );
             }
        
  • Closing Database Connection
    Finally it is necessary to disconnect from the database and release resources being used. If you don’t close the connection then in the production environment your application will fail due to hanging database connections. Here is the code for disconnecting the application from database:
      con.close();
       

In this section you learnt about the JDBC Steps necessary for performing database operations.

Output of program:

C:\vinod>javac RetriveAllEmployees.java

C:\vinod>java RetriveAllEmployees
Getting All Rows from employee table!
Employee Name:
Deepak Kumar
Harish Joshi
Rinku roy
Vinod Kumar

Download full code along with JDBC driver

                         

Facing Programming Problem?
Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

3 comments so far (post your own) View All Comments Latest 10 Comments:

This Site is worth a look through a very gainful and useful experience

Thank you

Posted by Minhaj on Saturday, 06.30.07 @ 17:29pm | #20440

Hi,

Since the field in the table are of string type:

`employee_name` varchar(50) NOT NULL,

So, the code is correct.

Thanks

Posted by Deepak Kumar on Thursday, 05.17.07 @ 19:19pm | #16275

The JDBC with MySQL is too good.
one small change in the following Url:
http://www.roseindia.net/jdbc/jdbc-steps.shtml:
-----------------------------------------------
Getting Results
In this step we receives the result of execute statement. In this case we will fetch the employees records from the recordset object and show on the console. Here is the code:
while (res.next()) {
String employeeName = res.getInt( " employee_name " );
System.out.println( employeeName );
}
-------------------------------------------------
here the Employee name is String not Integer.
it must be res.getString(employee_name");

thanks

Nag

Posted by Nag on Wednesday, 05.16.07 @ 22:10pm | #16166

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Hot Web Programming Job

Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.