JDBC Statement interface

The JDBC statement is used to execute queries against the database. Statement is an interface which provides the methods to execute queries. We can get a statement object by invoking the createStatement() method of Connection interface. Syntax:

Commonly used methods of Statement interface:

1. execute(String SQL): It is used to execute SQL DDL statements. Syntax:

2. executeQuery(String SQL): It is used to execute the select query and returns an object of ResultSet. Syntax:

3. executeUpdate(String SQL ): It is used to execute the query like inset, update, delete etc. It returns the no. of affected rows. Syntax:

4. executeBatch(): It is used to execute the batch of commands. Syntax:

JDBC Statement examples:

1. JDBC Statement creates a table example.

2. JDBC Statement inserts a record example.

3. JDBC Statement updates a record example.

4. JDBC Statement select records example.

5. JDBC Statement deletes a record example.

6. JDBC Statement batch update example.   Next Topic: JDBC Statement creates a table example. Previous Topic: Connect to MySql database with JDBC driver.

Content Protection by DMCA.com

  • Java Software
  • Java SE Downloads
  • Java SE 8 Documentation

Java JDBC API

The Java Database Connectivity (JDBC) API provides universal data access from the Java programming language. Using the JDBC API, you can access virtually any data source, from relational databases to spreadsheets and flat files. JDBC technology also provides a common base on which tools and alternate interfaces can be built.

The JDBC API is comprised of two packages:

You automatically get both packages when you download the Java Platform Standard Edition (Java SE) 8.

To use the JDBC API with a particular database management system, you need a JDBC technology-based driver to mediate between JDBC technology and the database. Depending on various factors, a driver might be written purely in the Java programming language or in a mixture of the Java programming language and Java Native Interface (JNI) native methods. To obtain a JDBC driver for a particular database management system, see JDBC Data Access API .

Enhancements in Java SE 8

Component : core-libs Sub-Component : java.sql:bridge Synopsis : The JDBC-ODBC Bridge has been removed. RFE : 7176225

Component : core-libs Sub-Component : java.sql Synopsis : JDBC 4.2 introduces the following features:

  • Addition of REF_CURSOR support.
  • Addition of java.sql.DriverAction Interface
  • >Addition of security check on deregisterDriver Method in DriverManager Class
  • Addition of the java.sql.SQLType Interface
  • Addition of the java.sql.JDBCType Enum
  • Add Support for large update counts
  • Changes to the existing interfaces
  • Rowset 1.2: Lists the enhancements for JDBC RowSet.

RFE : 8005080

Enhancements in Java SE 7

Component : core-libs Sub-Component : java.sql Synopsis : JDBC 4.1 introduces the following features:

  • The ability to use a try -with-resources statement to automatically close resources of type Connection , ResultSet , and Statement
  • RowSet 1.1: The introduction of the RowSetFactory interface and the RowSetProvider class, which enable you to create all types of row sets supported by your JDBC driver.

RFE : 6589685

Component : docs Sub-Component : release_notes Synopsis : The JDBC-ODBC Bridge will be removed in JDK 8. RFE : 8001747

More Information

  • JDBC Basics Tutorial
  • JDBC Home Page
  • Frequently Asked Questions about JDBC

what is statement interface in jdbc

Statement Interface in JDBC

  • Home > Java Technologies > JDBC
  • « Previous
  • Next »
  • JDBC Introduction
  • JDBC Driver
  • JDBC Database Connection Steps
  • JDBC DriverManager Class
  • JDBC Statement Interface
  • JDBC ResultSet Interface
  • JDBC Transactions
  • JDBC Batch Processing
  • JDBC RowSet Interface
  • JDBC Java Data Object (JDO)

Statement Interface

Statement interface methods, example : performing select operation with statement interface.

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class SelectTest {      public static void main(String[] args) throws Exception      {           Class.forName("oracle.jdbc.OracleDriver");           Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott","tiger");           Statement st = con.createStatement();           ResultSetrs = st.executeQuery("select * from student");           while(rs.next()!=false)           {                 System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4));           }           rs.close();           st.close();           con.close();      } }

PreparedStatement Interface

  • The PreparedStatement interface extends the Statement interface. It represents precompiled SQL statements and stores it in a PreparedStatement object.
  • It increases the performance of the application because the query is compiled only once.
  • The PreparedStatement is easy to reuse with new parameters.

Example : Insert operation with PreparedStatement Interface

import java.sql.*; class PreparedStatDemo {      public static void main(String args[])      {          try          {              Class.forName("oracle.jdbc.driver.OracleDriver");              Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","username", "password");               PreparedStatementps = con.prepareStatement("insert into Student values(?, ?, ?)");               ps.setInt(1, 101);               ps.setString(2, "Surendra");               ps.setString(3, "MCA");               ps.executeUpdate();               con.close();          }          catch(Exception e)          {               System.out.println(e);          }      } }

CallableStatement Interface

Example : callablestatement interface using stored procedure.

Creating stored procedure create or replace procedure "insertStudents"    (rollno IN NUMBER,   name IN VARCHAR2, course IN VARCHAR2)   is begin insert into Students values(rollno, name, course);   end;   / // ProcedureDemo.java import java.sql.*; classProcedureDemo {     public static void main(String args[])     {         try         {             Class.forName("oracle.jdbc.driver.OracleDriver");             Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott","tiger");             CallableStatementstmt = con.prepareCall("{call insertStudents(?, ?) }");             stmt.setInt(1, 101);             stmt.setString(2, Vinod);             stmt.setString(3, BE);             stmt.execute();             System.out.println("Record inserted successfully");             con.close();             stmt.close();         }         catch(Execption e)         {             e.printStackTrace();         }     } }

Related Topics

NOTE: The material in this chapter is based on JDBC tm API Tutorial and Reference, Second Edition: Universal Data Access for the Java tm 2 Platform , published by Addison Wesley as part of the Java series, ISBN 0-201-43328-1.

4.1 Statement Overview

A Statement object is used to send SQL statements to a database. There are actually three kinds of Statement objects, all of which act as containers for executing SQL statements on a given connection: Statement , PreparedStatement , which inherits from Statement , and CallableStatement , which inherits from PreparedStatement . They are specialized for sending particular types of SQL statements; a Statement object is used to execute a simple SQL statement with no parameters, a PreparedStatement object is used to execute a precompiled SQL statement with or without IN parameters, and a CallableStatement object is used to execute a call to a database stored procedure.

The Statement interface provides basic methods for executing statements and retrieving results. The PreparedStatement interface adds methods for dealing with IN parameters; the CallableStatement interface adds methods for dealing with OUT parameters.

In the JDBC 2.0 core API, the ResultSet interface has a set of new updateXXX methods and other new related methods that make it possible to update table column values programmatically. This new API also adds methods to the Statement interface (and PreparedStatement and CallableStatement interfaces) so that update statements may be executed as a batch rather than singly.

4.1.1 Creating Statement Objects

Once a connection to a particular database is established, that connection can be used to send SQL statements. A Statement object is created with the Connection method createStatement , as in the following code fragment:

Connection con = DriverManager.getConnection(url, "sunny", ""); Statement stmt = con.createStatement();

The SQL statement that will be sent to the database is supplied as the argument to one of the execute methods on a Statement object. This is demonstrated in the following example, which uses the method executeQuery :

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table2");

The variable rs references a result set that cannot be updated and in which the cursor can move only forward, which is the default behavior for ResultSet objects. The JDBC 2.0 core API adds a new version of the method Connection.createStatement that makes it possible to create Statement objects that produce result sets that are scrollable and/or updatable.

4.1.2 Executing Statements Using Statement Objects

The Statement interface provides three different methods for executing SQL statements: executeQuery , executeUpdate , and execute . The correct method to use is determined by what the SQL statement produces.

The method executeQuery is designed for statements that produce a single result set, such as SELECT statements.

The method executeUpdate is used to execute INSERT , UPDATE , or DELETE statements and also SQL DDL (Data Definition Language) statements like CREATE TABLE , DROP TABLE , and ALTER TABLE. The effect of an INSERT , UPDATE , or DELETE statement is a modification of one or more columns in zero or more rows in a table. The return value of executeUpdate is an integer (referred to as the update count) that indicates the number of rows that were affected. For statements such as CREATE TABLE or DROP TABLE , which do not operate on rows, the return value of executeUpdate is always zero.

The method execute is used to execute statements that return more than one result set, more than one update count, or a combination of the two. Because it is an advanced feature that the majority of programmers will never use, it is explained in its own section later in this overview.

All of the methods for executing statements close the calling Statement object's current result set if there is one open. This means that any processing of the current ResultSet object needs to be completed before a Statement object is re-executed.

It should be noted that the PreparedStatement interface, which inherits all of the methods in the Statement interface, has its own versions of the methods executeQuery , executeUpdate and execute . Statement objects do not themselves contain an SQL statement; therefore, one must be provided as the argument to the Statement.execute methods. PreparedStatement objects do not supply an SQL statement as a parameter to these methods because they already contain a precompiled SQL statement. CallableStatement objects inherit the PreparedStatement forms of these methods. Supplying a parameter to the PreparedStatement or CallableStatement versions of these methods will cause an SQLException to be thrown.

4.1.3 Statement Completion

When a connection is in auto-commit mode, the statements being executed within it are committed or rolled back when they are completed. A statement is considered complete when it has been executed and all its results have been returned. For the method executeQuery , which returns one result set, the statement is completed when all the rows of the ResultSet object have been retrieved. For the method executeUpdate , a statement is completed when it is executed. In the rare cases where the method execute is called, however, a statement is not complete until all of the result sets or update counts it generated have been retrieved.

Some DBMSs treat each statement in a stored procedure as a separate statement; others treat the entire procedure as one compound statement. This difference becomes important when auto-commit is enabled because it affects when the method commit is called. In the first case, each statement is individually committed; in the second, all are committed together.

4.1.4 Closing Statements

Statement objects will be closed automatically by the Java garbage collector. Nevertheless, it is recommended as good programming practice that they be closed explicitly when they are no longer needed. This frees DBMS resources immediately and helps avoid potential memory problems.

4.1.5 SQL Escape Syntax in Statements

Statement objects may contain SQL statements that use SQL escape syntax. Escape syntax signals the driver that the code within it should be handled differently. When escape processing is enabled (by calling Statement.setEscapeProcessing(true) or RowSet.setEscapeProcessing(true) ), the driver will scan for any escape syntax and translate it into code that the particular database understands. This makes escape syntax DBMS-independent and allows a programmer to use features that might not otherwise be available.

An escape clause is demarcated by curly braces and a key word, which indicates the kind of escape clause.

{keyword . . . parameters . . . }

The following keywords are used to identify escape clauses:

{escape 'escape-character'}
stmt.executeQuery("SELECT name FROM Identifiers WHERE Id LIKE ' \_% ' {escape ' \ ' }");
{fn concat("Hot", "Java")};
{fn user()};
{d 'yyyy-mm-dd'}
{t 'hh:mm:ss'} {ts 'yyyy-mm-dd hh:mm:ss.f . . .'}
{call procedure_name[(?, ?, . . .)]}

or, where a procedure returns a result parameter:

{? = call procedure_name[(?, ?, . . .)]}
{oj outer-join}
table {LEFT|RIGHT|FULL} OUTER JOIN {table | outer-join} ON search-condition
Statement stmt = con.createStatement("SELECT * FROM {oj TABLE1 LEFT OUTER JOIN TABLE2 ON DEPT_NO = 003420930}");

The method Statement.setEscapeProcessing turns escape processing on or off, with the default being on. A programmer might turn it off to cut down on processing time when performance is paramount, but it would normally be turned on. It should be noted that the method setEscapeProcessing does not work for PreparedStatement objects because the statement may have already been sent to the database before it can be called. See page 69 , the overview of the PreparedStatement interface, regarding precompilation.

4.1.6 Sending Batch Updates

The batch update facility provided by the JDBC 2.0 core API allows a Statement object to submit multiple update commands together as a single unit, or batch, to the underlying DBMS. This ability to submit multiple updates as a batch rather than having to send each update individually can improve performance greatly in some situations.

The following code fragment demonstrates how to send a batch update to a database. In this example, a new row is inserted into three different tables in order to add a new employee to a company database. The code fragment starts by turning off the Connection object con's auto-commit mode in order to allow multiple statements to be sent together as a transaction. After creating the Statement object stmt, it adds three SQL INSERT INTO commands to the batch with the method addBatch and then sends the batch to the database with the method executeBatch . The code looks like this:

Statement stmt = con.createStatement(); con.setAutoCommit(false); stmt.addBatch("INSERT INTO employees VALUES (1000, 'Joe Jones')"); stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')"); stmt.addBatch("INSERT INTO emp_dept VALUES (1000, '260')"); int [] updateCounts = stmt.executeBatch();

Because the connection's auto-commit mode is disabled, the application is free to decide whether or not to commit the transaction if an error occurs or if some of the commands in the batch fail to execute. For example, the application may not commit the changes if any of the insertions fail, thereby avoiding the situation where employee information exists in some tables but not in others.

In the JDBC 2.0 core API, a Statement object is created with an associated list of commands. This list is empty to begin with; commands are added to the list with the Statement method addBatch . The commands added to the list must all return only a simple update count. If, for example, one of the commands is a query (a SELECT statement), which will return a result set, the method executeBatch will throw a BatchUpdateException . A Statement object's list of commands can be emptied by calling the method clearBatch on it.

In the preceding example, the method executeBatch submits stmt's list of commands to the underlying DBMS for execution. The DBMS executes each command in the order in which it was added to the batch and returns an update count for each command in the batch, also in order. If one of the commands does not return an update count, its return value cannot be added to the array of update counts that the method executeBatch returns. In this case, the method executeBatch will throw a BatchUpdateException . This exception keeps track of the update counts for the commands that executed successfully before the error occurred, and the order of these update counts likewise follows the order of the commands in the batch.

In the following code fragment, an application uses a try / catch block, and if a BatchUpdateException is thrown, it retrieves the exception's array of update counts to discover which commands in a batch update executed successfully before the BatchUpdateException object was thrown.

try { stmt.addBatch("INSERT INTO employees VALUES (" + "1000, 'Joe Jones')"); stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')"); stmt.addBatch("INSERT INTO emp_dept VALUES (1000, '260')"); int [] updateCounts = stmt.executeBatch(); } catch(BatchUpdateException b) { System.err.println("Update counts of successful commands: "); int [] updateCounts = b.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i ++) { System.err.print(updateCounts[i] + " "); } System.err.println(""); }

If a printout was generated and looked similar to the following, the first two commands succeeded and the third one failed.

Update counts of successful commands: 1 1

JDBC drivers are not required to support batch updates, so a particular driver might not implement the methods addBatch , clearBatch , and executeBatch . Normally a programmer knows whether a driver that he/she is working with supports batch updates, but if an application wants to check, it can call the DatabaseMetaData method supportsBatchUpdates to find out. In the following code fragment, a batch update is used only if the driver supports batch updates; otherwise, each update is sent as a separate statement. The connection's auto-commit mode is disabled so that in either case, all the updates are included in one transaction.

con.setAutoCommit(false); if(dbmd.supportsBatchUpdates) { stmt.addBatch("INSERT INTO . . ."); stmt.addBatch("DELETE . . ."); stmt.addBatch("INSERT INTO . . ."); . . . stmt.executeBatch(); } else { System.err.print("Driver does not support batch updates; "); System.err.println("sending updates in separate statements."); stmt.executeUpdate("INSERT INTO . . ."); stmt.executeUpdate("DELETE . . ."); stmt.executeUpdate("INSERT INTO . . ."); . . . con.commit();

4.1.7 Giving Performance Hints

The Statement interface contains two methods for giving performance hints to the driver: setFetchDirection and setFetchSize . These methods are also available in the ResultSet interface and do exactly the same thing. The difference is that the Statement methods set the default for all of the ResultSet objects produced by a particular Statement object, whereas the ResultSet methods can be called any time during the life of the ResultSet object to change the fetch direction or the fetch size. See the section "Providing Performance Hints" on page 54 for a full discussion of these methods.

Both the Statement and ResultSet interfaces have the corresponding get methods: getFetchDirection and getFetchSize . If Statement.getFetchDirection is called before a fetch direction has been set, the value returned is implementation-specific, that is, it is up to the driver. The same is true for the method Statement.getFetchSize .

4.1.8 Executing Special Kinds of Statements

The execute method should be used only when it is possible that a statement may return more than one ResultSet object, more than one update count, or a combination of ResultSet objects and update counts. These multiple possibilities for results, though rare, are possible when one is executing certain stored procedures or dynamically executing an unknown SQL string (that is, unknown to the application programmer at compile time). For example, a user might execute a stored procedure (using a CallableStatement object), and that stored procedure could perform an update, then a select, then an update, then a select, and so on. In more typical situations, someone using a stored procedure will already know what it returns.

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Who implements Connection, ResultSet and Statement interfaces in this java program? [duplicate]

I recently found out that the Statement, Connection and the ResultSet used in the following program are interfaces. This program works completely fine but who implements these interfaces ?

Cyclops's user avatar

  • 3 They are implemented inside the oracle JDBC driver. –  Luiggi Mendoza Jun 16, 2013 at 18:37
  • The classes you're using. –  Dave Newton Jun 16, 2013 at 18:42
  • The classes you're instantiating, on the right side of = –  Curious Jun 16, 2013 at 19:34

5 Answers 5

Interfaces Statement, Connection and the ResultSet are finally implemented by the third party JDBC Driver provider.

Suppose if you are using MySQL Driver, this is how the hierarchy of implementation follows,

  • java.sql.Statement interface is finally implemented by com.mysql.jdbc.StatementImpl Class.

Internal implementation hierarchy:

com.mysql.jdbc.StatementImpl(Class) -->implements--> com.mysql.jdbc.Statement(interface) -->extends--> java.sql.Statement(interface)

  • java.sql.Connection interface is finally implemented by com.mysql.jdbc.JDBC4Connection Class.

com.mysql.jdbc.JDBC4Connection(Class) -->extends--> com.mysql.jdbc.ConnectionImp(Class) -->extends--> com.mysql.jdbc.ConnectionPropertiesImpl(Class) -->implements--> com.mysql.jdbc.MySQLConnection(Interface) -->extends--> com.mysql.jdbc.Connection(Interface) -->extends--> java.sql.Connection(Interface)

  • java.sql.ResultSet interface is finally implemented by com.mysql.jdbc.ResultSetImpl Class.

com.mysql.jdbc.ResultSetImpl(Class) -->implements--> com.mysql.jdbc.ResultSetInternalMethods(Interface) -->extends--> java.sql.ResultSet(Interface)

Sandeep Patange's user avatar

The JDBC API is implemented through the JDBC driver which are being provided by the various Database software vendors.

The JDBC Driver is a set of classes that implement the JDBC interfaces to process JDBC calls and return result sets to a Java application

Kartik73's user avatar

The JDBC driver provider provides the implementations you can do this. In this case Oracle.

BTW don't forget to close off your resources when you have finished with them or you can get a memory elak.

Peter Lawrey's user avatar

Implementation of these type of interface is vendor specific. For example if you are using Mysql and you have put Mysql Jar in classpath then Implementation classes are as per following:

Chintan Patel's user avatar

The database vendors provide the 3rd party drivers through which JDBC-ODBC driver communicates with the database. these 3rd party drivers have certain classes that implements the interfaces and writes their body according to the requirement. so the body of the drivers is changed when u move from mysql database to oracle database.

Debpratim Ghosh's user avatar

Not the answer you're looking for? Browse other questions tagged java interface or ask your own question .

  • Featured on Meta
  • Our Design Vision for Stack Overflow and the Stack Exchange network
  • Temporary policy: Generative AI (e.g., ChatGPT) is banned
  • Call for volunteer reviewers for an updated search experience: OverflowAI Search
  • Discussions experiment launching on NLP Collective

Hot Network Questions

  • Idiom for frustrating someone else's plans by taking what the other person wanted in the first place
  • Coworker keeps telling me where to sit. How can I handle this?
  • Parity and the Axiom of Choice
  • What だってそうだろう means here?
  • Why are hangars so high?
  • Is there any way I can recycle a device that has been iCloud locked?
  • Why do some US senators, like Joe Biden, Mitch McConnell, Dianne Feinstein, etc., last for so long in the Senate?
  • Could a planet orbiting a star have a habitable moon and this moon have its own moon orbiting it?
  • Correct way to play Mozart K331 Trio Measure 11?
  • Documents needed by German citizen traveling by land from the U.S. to Canada and back to the U.S
  • What comes first - apple in honey or pomegranate?
  • Why 2 thermostats of different rating in series in heater circuit?
  • How is the full-wave bridge rectifier still functioning?
  • Hypotheses Testing - Correlation vs. Regression
  • Stellarium and the Taurids
  • How can I pass a statistics exam that overly relies on memorizing formulas?
  • How did peer discovery work in Bitcoin v0.1?
  • Did the Z8000 ever hit the home computer market?
  • How do you deal with movement inertia in an environment after a step?
  • Question about number format for numbers between zero and one
  • Making single digit numbers between 1 and 9 into double digits, inside CSV file
  • Can I get an EASA Class 2 medical if I have monocular vision?
  • Young adult book series about kids who get different powers when they turn a certain age and their blood turns silver
  • Why isn't the penetrating depth of electromagnetic radiation consistent with its frequency?

what is statement interface in jdbc

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

  • Coding Ground
  • Corporate Training
  • Trending Categories

Data Structure

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

What is Statement in JDBC?

The Statement interface represents the static SQL statement, it is used to create and execute general purpose SQL statements using Java programs.

Creating a statement

You can create an object of this interface using the createStatement() method of the connection interface. Create a statement by invoking this method as shown below.

Executing the Statement object

Once you have created the statement object you can execute it using one of the execute methods namely, execute(), executeUpdate() and, executeQuery().

execute(): This method is used to execute SQL DDL statements, it returns a boolean value specifying weather the ResultSet object can be retrieved.

executeUpdate(): This method is used to execute statements such as insert, update, delete. It returns an integer value representing the number of rows affected.

executeQuery(): This method is used to execute statements that returns tabular data (example SELECT statement). It returns an object of the class ResultSet.

Following JDBC application demonstrates how to create and, execute a statement.

Nancy Den

  • Related Articles
  • What is JDBC?
  • What is the use of setFetchSize() and setMaxRows() methods of the JDBC Statement Interface?
  • What is CLOSE_CURSORS_AT_COMMIT in JDBC?
  • What is PreparedStatement in JDBC?
  • What is CallableStatement in JDBC?
  • What is ResultSet holdability in JDBC?
  • What is batch processing in JDBC?
  • What is Type_FORWARD_ONLY ResultSet in JDBC?
  • What is TYPE_SCROLL_INSENSITIVE ResultSet in JDBC?
  • What is TYPE_SCROLL_SENSITIVE ResultSet in JDBC?
  • What is ResultSet Concurrency in JDBC?
  • What is DatabaseMetaData in JDBC? What is its significance?
  • What is ResultSetMetaData in JDBC? What is its significance?
  • What is a CachedRowSet in JDBC? Explain?
  • What is RowId object in JDBC Explain?

Tutorials Point

JDBC interfaces for executing SQL

You execute SQL statements in a traditional SQL program to update data in tables, retrieve data from the tables, or call stored procedures. To perform the same functions in a JDBC program, you invoke methods.

With the IBM® Data Server Driver for JDBC and SQLJ , the PreparedStatement interface can be used to call stored procedures that have input parameters and no output parameters, and that return no result sets. However, the preferred interface is CallableStatement .

The CallableStatement interface can be used to call stored procedures with input parameters, output parameters, or input and output parameters, or no parameters. With the IBM Data Server Driver for JDBC and SQLJ , you can also use the Statement interface to call stored procedures, but those stored procedures must have no parameters.

  • The ResultSet interface provides access to the results that a query generates. The ResultSet interface has the same purpose as the cursor that is used in SQL applications in other languages.

BTech Geeks

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?

Commonly used methods of statement interface.

  • JDBC Statement Interface Example

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.

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:

  • CallableStatement in Java
  • PreparedStatement in Java
  • Java Continue Statement with Example
  • Java Break Statement with Example

Here is my empty database:

Statement Interface in Java 1

JDBC Statement Interface Example:

Statement Interface in Java 2

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Write an Interview Experience
  • Share Your Campus Experience
  • Introduction to Hibernate Framework
  • Mini Banking Application in Java
  • JDBC – Type 3 Driver
  • Working with Large Objects Using JDBC in Java
  • Standard Steps to Be Followed For Developing JDBC Application
  • JDBC – Type 2 Driver
  • JDBC Drivers
  • JDBC Tutorial
  • How to Call Stored Functions and Stored Procedures using JDBC?
  • Inserting Records in Batch Using JDBC
  • Hibernate Architecture
  • Getting Data From Microsoft Exchange Server in Java
  • Simplifying CRUD Operation with JDBC
  • Difference between ODBC and JDBC
  • What is RowSet in Java JDBC?
  • Types of Statements in JDBC
  • JDBC – Type 4 Driver
  • How to Use PreparedStatement in Java?
  • Implementation of Materialized view through the Java Program
  • Performing Database Operations in Java | SQL CREATE, INSERT, UPDATE, DELETE and SELECT
  • Arrays in Java
  • Spring Boot - Start/Stop a Kafka Listener Dynamically
  • Parse Nested User-Defined Functions using Spring Expression Language (SpEL)
  • Split() String method in Java with examples
  • Arrays.sort() in Java with examples
  • For-each loop in Java
  • Reverse a string in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • How to iterate any Map in Java
  • HashMap in Java

Establishing JDBC Connection in Java

Before establishing a connection between the front end i.e your Java Program and the back end i.e the database we should learn what precisely a JDBC is and why it came into existence. Now let us discuss what exactly JDBC stands for and will ease out with the help of real-life illustration to get it working.  

What is JDBC?  

JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC ( Open Database Connectivity ). JDBC is a standard API specification developed in order to move data from frontend to the backend. This API consists of classes and interfaces written in Java. It basically acts as an interface (not the one we use in Java) or channel between your Java program and databases i.e it establishes a link between the two so that a programmer could send data from Java code and store it in the database for future use.

Illustration: Working of JDBC co-relating with real-time

Why JDBC Come into Existence?  

As previously told JDBC is an advancement for ODBC, ODBC being platform-dependent had a lot of drawbacks. ODBC API was written in C, C++, Python, and Core Java and as we know above languages (except Java and some part of Python )are platform-dependent. Therefore to remove dependence, JDBC was developed by a database vendor which consisted of classes and interfaces written in Java. 

Steps For Connectivity Between Java Program and Database

  • Import the Packages
  • Load the drivers using the forName() method 
  • Register the drivers using DriverManager 
  • Establish a connection using the Connection class object
  • Create a statement
  • Execute the query
  • Close the connections

Let us discuss these steps in brief before implementing by writing suitable code to illustrate connectivity steps for JDBC/

Step 1: Import the Packages

Step 2: Loading the drivers 

In order to begin with, you first need to load the driver or register it before using it in the program. Registration is to be done once in your program. You can register a driver in one of two ways mentioned below as follows:

2-A Class.forName()

Here we load the driver’s class file into memory at the runtime. No need of using new or create objects. The following example uses Class.forName() to load the Oracle driver as shown below as follows:

2-B DriverManager.registerDriver()

DriverManager is a Java inbuilt class with a static member register. Here we call the constructor of the driver class at compile time. The following example uses DriverManager.registerDriver()to register the Oracle driver as shown below: 

 Step 3: Establish a connection using the Connection class object

After loading the driver, establish connections as shown below as follows: 

  • user: U sername from which your SQL command prompt can be accessed.
  • password: password from which the SQL command prompt can be accessed.
  • con: It is a reference to the Connection interface.
  • Url : Uniform Resource Locator which is created as shown below:

Where oracle is the database used, thin is the driver used, @localhost is the IP Address where a database is stored, 1521 is the port number and xe is the service provider. All 3 parameters above are of String type and are to be declared by the programmer before calling the function. Use of this can be referred to form the final code.

Step 4: Create a statement 

Once a connection is established you can interact with the database. The JDBCStatement, CallableStatement, and PreparedStatement interfaces define the methods that enable you to send SQL commands and receive data from your database.  Use of JDBC Statement is as follows: 

Note: Here, con is a reference to Connection interface used in previous step .

Step 5: Execute the query 

Now comes the most important part i.e executing the query. The query here is an SQL Query. Now we know we can have multiple types of queries. Some of them are as follows: 

  • The query for updating/inserting a table in a database.
  • The query for retrieving data.

The executeQuery() method of the Statement interface is used to execute queries of retrieving values from the database. This method returns the object of ResultSet that can be used to get all the records of a table.  The executeUpdate(sql query) method of the Statement interface is used to execute queries of updating/inserting.

Pseudo Code:

Here sql is SQL query of the type String

name of the student is retrieved from database

Step 6: Closing the connections  

So finally we have sent the data to the specified location and now we are on the verge of completing our task. By closing the connection, objects of Statement and ResultSet will be closed automatically. The close() method of the Connection interface is used to close the connection. It is shown below as follows:

This article is contributed by Shreya Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.

Please Login to comment...

  • zack_aayush
  • solankimayank
  • surinderdawra388
  • sumitgumber28
  • champsrohit19
  • vaghelaviral4

what is statement interface in jdbc

Improve your Coding Skills with Practice

Javastudypoint

Statement Interface in Java

What is statement interface in jdbc, statement interface methods:.

Statement Interface in Java

jdbc statement example:

Statement Interface in Java

You May Also Like

No comments:, recent posts, popular posts.

Java nested-if statement with Example

Random Posts

Our services.

Copyright (c) 2023 Javastudypoint.com All Right Reseved

Javatpoint Logo

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h [email protected] , to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • Graphic Designing
  • Digital Marketing
  • On Page and Off Page SEO
  • Content Development
  • Corporate Training
  • Classroom and Online Training

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] . Duration: 1 week to 2 week

RSS Feed

IMAGES

  1. Callable Statement Example

    what is statement interface in jdbc

  2. Statement Interface in Java

    what is statement interface in jdbc

  3. Java JDBC Statement Interface Example with MySQL Database

    what is statement interface in jdbc

  4. JDBC Tutorial 4

    what is statement interface in jdbc

  5. JDBC Statement

    what is statement interface in jdbc

  6. Hướng dẫn Java JDBC, Ví dụ với Statement trong JDBC

    what is statement interface in jdbc

VIDEO

  1. What is JDBC

  2. WAS7 Part 2

  3. 7. JDBC Prepared Statement

  4. 6. Виконання SQL запитів за допомогою JDBC Statement

  5. 8 Improve JDBC Code

  6. JDBC (Java Data Base Connectivity) Introduction || By Mr. M. Yakub

COMMENTS

  1. JDBC Statement interface

    Statement is an interface which provides the methods to execute queries. We can get a statement object by invoking the createStatement () method of Connection interface. Syntax: Statement stmt=conn.createStatement (); Commonly used methods of Statement interface: 1. execute (String SQL): It is used to execute SQL DDL statements. Syntax:

  2. Processing SQL Statements with JDBC

    Creating Statements. A Statement is an interface that represents a SQL statement. You execute Statement objects, and they generate ResultSet objects, which is a table of data representing a database result set. You need a Connection object to create a Statement object. For example, CoffeesTable.viewTable creates a Statement object with the ...

  3. Java Statement

    The Statement interface provides methods to execute queries with the database. The statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet. Commonly used methods of Statement interface: The important methods of Statement interface are as follows:

  4. Types of Statements in JDBC

    The statement interface is used to create SQL basic statements in Java it provides methods to execute queries with the database. There are different types of statements that are used in JDBC as follows: Create Statement Prepared Statement Callable Statement 1.

  5. Difference Between Statement and PreparedStatement

    However, they differ significantly from one another in features and performance: Statement - Used to execute string-based SQL queries. PreparedStatement - Used to execute parameterized SQL queries. To be able to use Statement and PreparedStatement in our examples, we'll declare the h2 JDBC connector as a dependency in our pom.xml file ...

  6. Java JDBC API

    The Java Database Connectivity (JDBC) API provides universal data access from the Java programming language. Using the JDBC API, you can access virtually any data source, from relational databases to spreadsheets and flat files. JDBC technology also provides a common base on which tools and alternate interfaces can be built.

  7. java

    Now you can get an instance of a class which implements the Statement interface from the Connection instance. Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM [yourtablename]"); .... For more examples just google around a bit (JDBC, java, [nameofyourdb]) For Connector/J there is a nice documentation herer

  8. Statement Interface in JDBC

    The Statement interface provides the method to execute the database queries. After making a connection, Java application can interact with database. The Statement interface contains the ResultSet object. Statement Interface Methods The Statement interface provides the following important methods:

  9. Statement

    The JDBC API supports ISO standard format for the syntax of these literals, using an escape clause that the driver must translate to the DBMS representation. For example, a date is specified in a JDBC SQL statement with the following syntax: {d 'yyyy-mm-dd'} In this syntax, yyyy is the year, mm is the month, and dd is the day.

  10. Who implements Connection, ResultSet and Statement interfaces in this

    9. Interfaces Statement, Connection and the ResultSet are finally implemented by the third party JDBC Driver provider. Suppose if you are using MySQL Driver, this is how the hierarchy of implementation follows, java.sql.Statement interface is finally implemented by com.mysql.jdbc.StatementImpl Class. Internal implementation hierarchy:

  11. JDBC

    The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your database. They also define methods that help bridge data type differences between Java and SQL data types used in a database. The following table provides a summary ...

  12. What are the main classes and interfaces of JDBC

    What are the main classes and interfaces of JDBC? Java 8 Programming Object Oriented Programming JDBC API is available in two packages java.sql, core API and javax.sql JDBC optional packages. Following are the important classes and interfaces of JDBC. Daniol Thomas Updated on 30-Jul-2019 22:30:25 0 Views Print Article Previous Page Next Page

  13. What is Statement in JDBC

    The Statement interface represents the static SQL statement, it is used to create and execute general purpose SQL statements using Java programs. Creating a statement You can create an object of this interface using the createStatement () method of the connection interface. Create a statement by invoking this method as shown below.

  14. Db2 12

    JDBC interfaces for executing SQL. You execute SQL statements in a traditional SQL program to update data in tables, retrieve data from the tables, or call stored procedures. To perform the same functions in a JDBC program, you invoke methods. Those methods are defined in the following interfaces: The Statement interface supports all SQL ...

  15. What is Java Database Connectivity(JDBC)

    Statement interface PreparedStatement interface CallableStatement interface ResultSet interface ResultSetMetaData interface DatabaseMetaData interface RowSet interface A list of popular classes of JDBC API are given below: DriverManager class Blob class Clob class Types class Why Should We Use JDBC

  16. Statement Interface in Java

    What is Statement Interface in JDBC? Commonly used Methods of Statement Interface JDBC Statement Interface 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.

  17. Introduction to JDBC (Java Database Connectivity)

    JDBC is an API (Application programming interface) used in java programming to interact with databases. The classes and interfaces of JDBC allow the application to send requests made by users to the specified database. Purpose of JDBC

  18. Establishing JDBC Connection in Java

    JDBC is an acronym for Java Database Connectivity. It's an advancement for ODBC ( Open Database Connectivity ). JDBC is a standard API specification developed in order to move data from frontend to the backend. This API consists of classes and interfaces written in Java.

  19. Statement Interface in Java

    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.

  20. Java Database Connectivity

    Java Database ConnectivityJDBC) is an application programming interface (API) for the programming language which defines how a client may access a . It is a Java-based data access technology used for Java database connectivity. It is part of the Java Standard Edition platform, from Oracle Corporation.

  21. Java Connection

    The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData, i.e., an object of Connection can be used to get the object of Statement and DatabaseMetaData. The Connection interface provide many methods for transaction management like commit (), rollback (), setAutoCommit (), setTransactionIsolation (), etc.