Executing a JDBC Statement
The following code fragment provides the syntax for executing a SQL INSERT statement using JDBC:
java.sql.Statementstatement
=connection
.createStatement( ); introwsInserter
=statement
.executeUpdate( "INSERT INTO authors(au_id, au_lname, au_fname, contract) " + " VALUES ('xyz', 'Brown', 'Emmit', 1)" );statement
.close( );
Executing a SQL statement first requires the creation of a JDBC
Statement
object. AStatement
object is produced by invoking thecreateStatement
method on a valid JDBCConnection
object:java.sql.Statement
statement
=connection
.createStatement( );After a
Statement
object has been created, a SQL statement can be executed by invoking one of the execute methods found on theStatement
object. For non-query statements, theexecuteUpdate
method is the best method to use:statement
.executeUpdate( "INSERT INTO authors(au_id, au_lname, " +"
au_fname, contract) VALUES " +"
('xyz', 'Brown', 'Emmit', 1)" );The
executeUpdate
method returns anint
value indicating the number of rows inserted, updated, or deleted during the execution of the SQL statement. If the execution fails, you will get aSQLException
.After the
Statement
object has been executed, it may be executed again, or freed by invoking theclose
method.
statement
.close( );
Get SQL in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.