What are different steps to connect any java application with the database in java using JDBC used in JDBC? Write down a small program showing all steps.

 There are 5 steps to connect any java application with the database in java using JDBC. They are as follows:

1. Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.

Syntax of for Name() method

public static void forName(String className) throws ClassNotFound Exception

Example to register the Driver class

Class.for Name("com.mysql.jdbc.Driver ")


2.Creating connection

The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax

public static Connection getConnection(db_url)or,

public static Connection getConnection(db_url, user_name, password)

Example to establish connection with the mySQL database

Connection con=DriverManager.getConnection("jdbc: mysql://Localhost/emp", "root", "arjun");


3.Creating a statement

The createStatement() method of the Connection interface is used to create a statement. The object of the statement is responsible to execute queries with the database.

Syntax

public Statement createStatement()

Example to create the statement object 

Statement stmt=con.createStatement();

4. Executing queries

 Once we have created a Statement object, we can use it to execute a SQL statement with one of its three execute methods.

a) boolean execute(String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. This method is used to execute SQL DDL statements or when we need to use truly dynamic SQL.

b) int execute Update(String SQL): Returns the numbers of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which we expect to get a number of rows affected for example, an INSERT, UPDATE, or DELETE statement.

Example to execute query

ResultSet rs=stmt. executeQuery("select from emp");

fi ResultSet executeQuery(String SQL): Returns a ResultSet object. Use this method when you expect to get a result set, as we would with a SELECT statement. 

Once the ResultSet is obtained, we can iterate through it as below:

while(rs.next())

{

System.out.println(rs.getInt (1) +""+rs.getString(2));

}

5. Closing connection

By closing the connection, the object statement and ResultSet will be closed automatically. The close method of the Connection interface is used to close the connection.

Syntax

public void close()

Example to close connection

con.close();


Complete Example

//STEP 1. Import required packages

import java.sql.*;

Public class ConnectDB

{

static final String JDBC_DRIVER = static final String DB_URL = "com.mysql.jdbc.Driver"; "jdbc:mysql://localhost/emp";

 public static void main(String[] args)

{

Connection conn = null;

try

{

Statement stmt = null;

//STEP 2: Register JDBC driver

Class. for Name("com.mysql.jdbc.Driver");

//STEP 3: Open a connection

System.out.println("Connecting to database..."); 

conn =DriverManager.getConnection (DB_URL, "root", "arjun");

//STEP 4: Execute a query

System.out.println("Creating statement...");

stmt = conn.createStatement ();

String sql;

sql = "SELECT eid, age, Fname, Lname FROM employees";

ResultSet rs = stmt.executeQuery (sql);

//STEP 5: Extract data from result set

while(rs.next())

{

//Retrieve by column name int id rs.getInt ("eid");

int age= rs.getInt("age");

String first = rs.getString("Fname"); String last = rs.getString("Lname");

//Display values

System.out.print("ID: + id);

System.out.print(", Age: + age);

System.out.print(", First Name: " + first);

System.out.println(", Last: Name " + last);

}

//STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close();

}

catch(SQLException se)

{

//Handle errors for JDBCINT se.printStackTrace();

}

catch (Exception e)

{

//Handle errors for Class.forName e.printStackTrace();

}

System.out.println("Goodbye!");

}//end main

}




                           OR,
The following 5 steps are the basic steps involve in connecting a Java application with Database using JDBC.

Register the Driver
Create a Connection
Create SQL Statement
Execute SQL Statement
Closing the connection



1. Register the Driver
It is first an essential part to create a JDBC connection. JDBC API provides a method Class.forName() which is used to load the driver class explicitly. For example, if we want to load a jdbc-odbc driver then we call it like the following.

Example to register with JDBC-ODBC Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

2. Create a Connection
After registering and loading the driver in step1, now we will create a connection using getConnection() method of DriverManager class. This method has several overloaded methods that can be used based on the requirement. Basically, it require the database name, username and password to establish connection. The syntax of this method is given below.

Syntax
getConnection(String url)
getConnection(String url, String username, String password)
getConnection(String url, Properties info)

3. Create SQL Statement
In this step we will create statement object using createStatement() method. It is used to execute the sql queries and defined in Connection class. Syntax of the method is given below.

Syntax
public Statement createStatement() throws SQLException

Example to create a SQL statement
Statement s=con.createStatement();

4. Execute SQL Statement
After creating statement, now execute using executeQuery() method of Statement interface. This method is used to execute SQL statements. Syntax of the method is given below.

Syntax
public ResultSet executeQuery(String query) throws SQLException

Example to execute a SQL statement
In this example, we are executing a sql query to select all the records from the user table and stored into resultset that further is used to display the records.

ResultSet rs=s.executeQuery("select * from user");
  while(rs.next())
  {
   System.out.println(rs.getString(1)+" "+rs.getString(2));
 }

5. Closing the connection
This is the final step which includes closing all the connections that we opened in our previous steps. After executing the SQL statement you need to close the connection and release the session. The close() method of the Connection interface is used to close the connection.

Syntax
public void close() throws SQLException

Example of closing a connection
con.close();


Now lets combine all these steps into a single example and create a complete example of JDBC connectivity.

Example: All Steps into one place
import java.sql.*;
class Test {
 public static void main(String[] args) {
  try {
   //Loading driver
   Class.forName("oracle.jdbc.driver.OracleDriver");

   //creating connection
   Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "username", "password");

   Statement s = con.createStatement(); //creating statement

   ResultSet rs = s.executeQuery("select * from Student"); //executing statement

   while (rs.next()) {
    System.out.println(rs.getInt(1) + " " + rs.getString(2));
   }

   con.close(); //closing connection
  } catch (Exception e) {
   e.printStacktrace();
  }
 }
}


Comments

Popular posts from this blog

What are different steps used in JDBC? Write down a small program showing all steps.

Discuss classification or taxonomy of virtualization at different levels.

Pure Versus Partial EC