Statement Interface in Java – JDBC | Definition, Syntax, and Methods of Statement Interface with Example

In this tutorial, you will learn Statement Interface in Java-JDBC. With the help of the Statement object, we can send our SQL Query to Database. Furthermore, you will also read Statement interface methods with an example.

What is Statement Interface in JDBC?

In JDBC Statement is an Interface. By using the Statement object, we can send our SQL Query to Database. At the time of creating a Statement object, we don’t need to provide any Query. Statement object can work only for the static query.

Whenever we are applying an execute() method, every time Query will be compiled and executed. As Query will be compiled every time, its performance is low. Best choice for Statement object, if you want to work with multiple queries.

Syntax:

Statement stmt=conn.createStatement();

Commonly used Methods of Statement Interface

The important methods of Statement Interface are given below:

1. public boolean execute(String url): This method is used for all types of SQL statements (eg. Select, Insert, Update, etc.). This method returns a boolean value. If you don’t know which method is used (executeQuery() or executeUpdate()) then you should go for execute() method.

2. public ResultSet executeQuery(String url): This method is used for the Select a statement which retrieves some data from the database. This method returns a ResultSet object.

3. public int executeUpdate(String url): If you want to modify in your database, then you should go for the executeUpdate() method. This method returns an int value which indicates the number of rows affected.

4. public int[] executeBatch(): This method is used the execute the batch of commands. This method returns an integer array.

Also Refer:

Here is my empty database:

Statement Interface in Java 1

JDBC Statement Interface Example:

import java.sql.*;
import java.util.*;
class InsertMultipleRows{
public static void main(String args[])throws Exception{
class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/emp_record","root"," ");
Statement st = con.createStatement();
Scanner sc = new Scanner(System.in);

while(true){
System.out.println("Enter employee number: ")
int eno = sc.nextInt();
System.out.println("Enter employee name: ")
String ename = sc.next();
System.out.println("Enter employee salary: ")
double esal = sc.nextDouble();
System.out.println("Enter employee address: ")
String eaadr = sc.next();

String sqlquery = String.format("insert into insert_rows values(%d,%s,%f.%s)", eno,ename,esal,eaddr);
st.excecuteUpdate(sqlquery);
System.out.println("Record inserted succesfully ");
System.out.println("Do you want to insert more records[yes/no]");
String option = sc.next();
if(option.equalsIgnoreCase("no")){
break;
}
}
}
}

Output:

Statement Interface in Java 2

Statement Interface in Java 3