September 2004
Intermediate to advanced
710 pages
24h 25m
English
The following Java code fragment executes a SQL INSERT statement that adds new sales to the sales table in the pubs database. The INSERT statement is parameterized to provide better performance.
// Create a Command object for the SQL statement PreparedStatementstatement=connection.prepareStatement( "INSERT INTO SALES(stor_id, ord_num, ord_date, qty, payterms, title_id) " + "VALUES(?, ?, ?, ?, ?, ?)" ); while( getNextSale(statement) ) { // Execute the statement int result =statement.executeUpdate( ); if( result != 1 ) { // If result isn't 1, then the insert failed. System.out.println( "The INSERT failed." ); break; } }
Create a JDBC PreparedStatement object and pass
the parameterized SQL statement into its constructor. The difference
for using bound parameters within the statement is in the
VALUES clause of the INSERT
statement. Contained within the VALUES clause
are six placeholders (the question marks) for the parameters that
will later be bound to the PreparedStatement
object.
PreparedStatementstatement=connection.prepareStatement( "INSERT INTO SALES(stor_id, ord_num, ord_date, qty, payterms, title_id) " + "VALUES(?, ?, ?, ?, ?, ?)" );
In this example, the parameters are assigned a value by the
user-defined getNextSale function call, which
could be implemented like this:
static boolean getNextSale( PreparedStatement statement ) throws SQLException { // Omitted is the code ...Read now
Unlock full access