Statement interface

In this chapter you will learn:

  1. Create and use Statement Object
  2. Execute SQL Statements
  3. Closing Statement Obeject

Creating Statement Object

We can use the Connection object's createStatement() method to create an object of Statement.

The following code shows a general structure of using Statement

Statement stmt = null;//java 2  s .  com
try {
   stmt = conn.createStatement( );
   stmt.executeUpdate(...);
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   . . .
   
}

Execute SQL Statements

Once we have the Statement object, we can execute a SQL statement with one of its three execute methods.

  • boolean execute(String SQL) Returns a boolean value of true if ResultSet is ready.
  • int executeUpdate(String SQL) Returns the numbers of rows changed by the SQL statement. We usually use this method for INSERT, UPDATE, or DELETE statement.
  • ResultSet executeQuery(String SQL) Returns a ResultSet object. We usually use this method for a SELECT statement.

Closing Statement Obeject

After using the Statement object we have to close the Statement object by calling the close() method.

Statement stmt = null;/*from j a  va 2  s . c  o m*/
try {
   stmt = conn.createStatement( );
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   stmt.close();
}

If the Connection object is closed it will close the Statement object as well.

Next chapter...

What you will learn in the next chapter:

  1. How to add records to a table
Home » Java Tutorial » Statements, ResultSet, Exception, Warning

Statement

    Three types of statements
    Statement interface
    Insert
    Delete records
    Drop a table
    Batch operation

PreparedStatement

    PreparedStatement
    Insert
    Delete
    Update with parameters
    Batch operation
    ParameterMetaData
    Fetch size
    Set null vaue

CallableStatement

    CallableStatement

ResultSet

    ResultSet
    ResultSet Type
    ResultSet Concurrency
    Create a ResultSet
    ResultSet reading
    ResultSet get by column name
    ResultSet get column by index
    ResultSet next row
    ResultSet table row count
    ResultSet navigation
    ResultSet cursor forward and backward
    ResultSet first
    ResultSet last
    ResultSet after last
    ResultSet before first
    ResultSet absolute(2)
    ResultSet absolute(-1)
    ResultSet relative(-2)
    ResultSet relative(-2)
    ResultSet update
    Column Names
    Column count
    Column Characteristics

ResultSetMetaData

    Column Names
    Column count
    Column Characteristics

SQL Exception, SQL Warning

    SQL Exception
    SQLException information
    Chaining SQLExceptions
    Connection Warning
    PreparedStatement SQLWarning
    Statement SQLWarning
    ResultSet warning
    SQLWarning information