Sunday 9 June 2013

JDBC Statement

Tags

Once you have created a Connection, you can begin using it to execute SQL statements. This is usually done via Statement objects. There are actually three kinds of statements in JDBC:

1. Statement
JDBC Statement object is used to send your SQL statements to the DBMS, and should not to be confused with an SQL statement. A JDBC Statement object is associated with an open connection, and not any single SQL Statement. You can think of a JDBC Statement object as a channel sitting on a connection, and passing one or more of your SQL statements (which you ask it to execute) to the DBMS.

An active connection is needed to create a Statement object. To get a Statement object, call the createStatement( ) method of a Connection:

Syntax
Statement stmt = con.createStatement() ;

2.Prepared Statement
The PreparedStatement object is a close relative of the Statement object. Both accomplish roughly the same thing: running SQL statements. PreparedStatement, however, allows you to precompile your SQL and run it repeatedly, adjusting specific parameters as necessary. Since processing SQL strings is a large part of a database's overhead, getting compilation out of the way at the start can significantly improve performance. As with Statement, you create a PreparedStatement object from a Connection object. In this case, though, the SQL is specified at creation instead of execution, using the prepareStatement( ) method of Connection:

Syntax
PreparedStatement pstmt = con.prepareStatement("INSERT INTO EMPLOYEES (NAME, PHONE) VALUES (?, ?)");

3.Callable Statement
Represents a stored procedure. Can be used to execute stored procedures in a RDBMS, which supports them. A stored procedure is stored in a database; the call to the stored procedure is what a CallableStatement object contains. This call is written in an escape syntax that may take one of two forms: one form with a result parameter, and the other without one. A result parameter, a kind of OUT parameter, is the return value for the stored procedure.

Syntax
CallableStatement cstmt = con.prepareCall("{call procedure_name(?, ?)}");


EmoticonEmoticon