English 中文(简体)
Java & MySQL - Statement
  • 时间:2024-12-22

Java & MySQL - Statement


Previous Page Next Page  

JDBC Statement interface defines the methods and properties to enable send SQL commands to MySQL database and retrieve data from the database. Statement is used for general-purpose access to your database. It is useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters.

Before you can use a Statement object to execute a SQL statement, you need to create one using the Connection object s createStatement( ) method, as in the following example −


Statement stmt = null;
try {
   stmt = conn.createStatement( );
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   . . .
}

Once you ve created a Statement object, you can then use it to execute an SQL statement with one of its three execute methods.

    boolean execute (String SQL) − Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL.

    int executeUpdate (String SQL) − Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement.

    ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement.

Closing Statement Object

Just as you close a Connection object to save database resources, for the same reason you should also close the Statement object.

A simple call to the close() method will do the job. If you close the Connection object first, it will close the Statement object as well. However, you should always exppcitly close the Statement object to ensure proper cleanup.


Statement stmt = null;
try {
   stmt = conn.createStatement( );
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   stmt.close();
}

We re using try with resources which handles the resource closure automatically. Following example demonstrates all of the above said concepts.

This code has been written based on the environment and database setup done in the previous chapter.

Copy and paste the following example in TestApppcation.java, compile and run as follows −


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

pubpc class TestApppcation {
   static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
   static final String USER = "guest";
   static final String PASS = "guest123";
   static final String QUERY = "SELECT id, first, last, age FROM Employees";
   static final String UPDATE_QUERY = "UPDATE Employees set age=30 WHERE id=103";

   pubpc static void main(String[] args) {
      // Open a connection
      try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
         Statement stmt = conn.createStatement();
         ) {
         // Let us check if it returns a true Result Set or not.
         Boolean ret = stmt.execute(UPDATE_QUERY);
         System.out.println("Return value is : " + ret.toString() );

         // Let us update age of the record with ID = 103;
         int rows = stmt.executeUpdate(UPDATE_QUERY);
         System.out.println("Rows impacted : " + rows );

         // Let us select all the records and display them.
         ResultSet rs = stmt.executeQuery(QUERY);		      

         // Extract data from result set
         while (rs.next()) {
            // Retrieve by column name
            System.out.print("ID: " + rs.getInt("id"));
            System.out.print(", Age: " + rs.getInt("age"));
            System.out.print(", First: " + rs.getString("first"));
            System.out.println(", Last: " + rs.getString("last"));
         }
         rs.close();
      } catch (SQLException e) {
         e.printStackTrace();
      } 
   }
}

Now let us compile the above example as follows −


C:>javac TestApppcation.java
C:>

When you run TestApppcation, it produces the following result −


C:>java TestApppcation
Return value is : false
Rows impacted : 1
ID: 100, Age: 18, First: Zara, Last: Ap
ID: 101, Age: 25, First: Mehnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 30, First: Sumit, Last: Mittal
C:>
Advertisements