Tuesday, July 5, 2011

Using Statements in Jdbc

A Statement is obtained from a Connection:
Statement stmt = con.createStatement() ;
Once you have a Statement, you can use it to execute, and control the execution of, various kinds of SQL queries.

  • Use stmt.executeUpdate with a string argument containing the text of an SQL update query (INSERT, DELETE or UPDATE). This returns an integer count of the number of rows updated.
  • Use stmt.executeQuery with a string argument containing the text of an SQL SELECT query. This returns a ResultSet object which is used to access the rows of the query results.
  • You can use stmt.execute to execute an arbitrary SQL statement which may be of any type. However, extracting the results, whether an integer or a ResultSet, is less convenient. This is usually only used where you want a generalized access to the database that allows programmatic generation of queries.
    int count = stmt.executeUpdate("INSERT INTO Customers " +
                          "(CustomerFirstName, CustomerLastName, CustomerAddress) "
                          "VALUES ('Tony', 'Blair', '10 Downing Street, London')") ;
    ResultSet rs = stmt.executeQuery("SELECT * FROM Customers") ;
    // do something with count and RS


The syntax of the SQL string passed as an argument must match the syntax of the database being used. In particular, appropriate quoting of special characters must be used. For example, if a name, O'Neill, is to be inserted, it has to be entered as
ResultSet rs = stmt.executeQuery("SELECT * FROM Customers" +
                                 "WHERE CustomerLastName = 'O''Neill'") ;

No comments:

Post a Comment

Chitika