Monday, 12 February 2018

JDBC Statement Interface in Java with Example ~ foundjava

Statement Interface in JDBC

Statement Interface in Java

In this jdbc tutorial, We are gonna to discuss jdbc Statement interface in java with example so that you can understand what is the roll of Statement interface in jdbc.

Jdbc Statement interface is used to execute queries with the database by using some methods which is provided by Statement interface.

After making connection with the database by using Connection interface we can get the object of a Statement interface by using createStatement() method of Connection interface e.g...

Statement stm = con.createStatement();

By using Statement interface methods, You can retrieve, insert, delete and update data into the database.


Mostly Used Methods of Statement Interface

There are some methods of Statement interface which is used to execute queries with the databse.

1) public ResultSet executeQuery(String sql)

It is used to execute the select query and returns the object of ResultSet.

2) public int executeUpdate(String sql)

It is used to execute the query like create, insert, delete and update.

3) public boolean execute(String sql)

It is used to execute query that may return multiple results.

4) public int[] executeBatch()

It is used to execute batch of commands.

Let's understand Statement interface by simple example.




JDBC Statement Interface Example

In this example, we are going to fetch all the record from database table by executing select query with the help of executeQuery() method. You can execute query like create, insert, update, delete etc. But here we will execute only select query.

Suppose there is a table(student table with age and name) in the oracle database with some records.

import java.sql.*;
class Demo
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "system", "bca");

Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select * from student");

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

catch(Exception e)
{
System.out.println(e);
}
}
}

Here we saw a simple example of java jdbc Statement interface.

No comments:

Post a Comment