Statement Interface in Java - Javastudypoint

Monday, September 3, 2018

Statement Interface in Java

In this tutorial, you will learn Statement Interface in JDBC. By using Statement object we can send our SQL Query to Database.you will also learn Statement interface methods.

What is Statement Interface in JDBC?

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

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

Statement Interface Methods:

The important methods of Statement Interface are given below:

1) public boolean execute(String url): This method is used for all type of SQL statement (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 executeUpdate() method. This method returns an int value which indicates a number of rows affected.

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


Here is my empty database:
                                 
Statement Interface in Java

jdbc statement 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



Statement Interface in Java








No comments:

Post a Comment