Sunday, 13 July 2014

JDBC Statement

Enjoying Our Java Tutorials?

Subscribe to our YouTube channel for clear, step-by-step Java and database programming guides!

SUBSCRIBE NOW

What is a JDBC Statement?

In Java Database Connectivity (JDBC), the Statement interface is the fundamental bridge used to send SQL commands to your relational database. Once your Java program establishes a connection using DriverManager, you can create a Statement object directly from that connection instance.

A standard Statement object is primarily designed for executing general, static SQL queries where parameter values do not change dynamically at runtime.

How to Create a Statement Object

Creating a statement is straightforward. You call the createStatement() method on your active Connection object:

Connection connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();

Key Methods in the Statement Interface

The Statement interface provides specialized methods depending on the type of SQL command you want to run:

  • executeQuery(String sql): Used for SELECT queries. It executes the query and returns a tabular ResultSet containing the matched data records.
  • executeUpdate(String sql): Used for DML statements like INSERT, UPDATE, DELETE, or DDL statements like CREATE TABLE and DROP TABLE. It returns an integer representing the number of rows affected.
  • execute(String sql): A universal method used when a query might return multiple result sets or update counts, typically in dynamic or complex operations.

When Should You Use Statement?

The basic Statement interface is best suited for:

  1. One-time static SQL statements (such as creating tables, altering tables, or dropping databases).
  2. Simple test scripts or prototype applications where queries do not accept user input directly.
  3. Batch queries containing fixed, non-repeating SQL statements.

Related Tutorials You Might Like


Click here to watch in Youtube : https://www.youtube.com/watch?v=8P596TNw83A

Click the below Image to Enlarge
JDBC Statement

JDBC Statement

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • 1 comment:

    Tutorials