+ All Categories
Home > Documents > Jdbc _Intro 2.ppt

Jdbc _Intro 2.ppt

Date post: 03-Oct-2015
Category:
Upload: lavanya123
View: 20 times
Download: 1 times
Share this document with a friend
57
1 JDBC ver 1.0
Transcript
Chapter 9: Objects and Classes*
JDBC is a Java API for executing SQL statements. (As a point of interest, JDBC is a trademarked name and is not an acronym; nevertheless, JDBC is often thought of as standing for "Java Database Connectivity".) It consists of a set of classes and interfaces written in the Java programming language. JDBC provides a standard API for tool/database developers and makes it possible to write database applications using a pure Java API.
With an application written in the Java programming language, one doesn't have to worry about writing different applications to run on different platforms. The combination of Java and JDBC lets a programmer write it once and run it anywhere.
Simply put, JDBC makes it possible to do three things:
* establish a connection with a database
* send SQL statements
* process the results.
jdbc is a “generic SQL database access framework” in Java
allows applications to query databases, and manipulate data returned from them
it is based on X/Open SQL Call Level Interface(CLI) standard (ODBC is also based on the CLI)
JDBC: An Intro
*
Structured Query Language (SQL) is the standard language for accessing relational databases. One area of difficulty is that although most DBMSs (DataBase Management Systems) use a standard form of SQL for basic functionality, they do not conform to the more recently-defined standard SQL syntax or semantics for more advanced functionality.
One way the JDBC API deals with this problem is to allow any query string to be passed through to an underlying DBMS driver. This means that an application is free to use as much SQL functionality as desired, but it runs the risk of receiving an error on some DBMSs. In fact, an application query need not even be SQL, or it may be a specialized derivative of SQL designed for specific DBMSs.
*
Key Features
Included in the java platform
SLC - Our People Makes The Difference
*
1. It uses the existing enterprise resources.
2. Reduced development time for the application.
3. JDBC supports networking for distributed clients.
4. It provides full access to the metadata of the database.
5. No installation is required. Classes can be loaded at runtime also.
6. Uses easy syntax to identify the databases(URL style).
7. Included in JSDK.
Net-Protocol All-Java Driver (Type 3)
Native Protocol All-Java Driver (Type 4)
Java.sun.com/products/jdbc/jdbcdrivers.html
*
TYPE-1 No Direct
TYPE-2 No Direct
JDBC ver 1.0
JDBC driver types
JDBC drivers are divided into four types or levels. Each type defines
a JDBC driver implementation with increasingly higher levels of
platform independence, performance, and deployment administration.
The four types are:
Type 3: Net-protocol/all-Java driver
Type 4: Native-protocol/all-Java driver
The type 1 driver, JDBC-ODBC Bridge, translates all JDBC calls
into ODBC (Open DataBase Connectivity) calls and sends them to the
ODBC driver. As such, the ODBC driver, as well as, in many cases, the
client database code, must be present on the client machine.
JDBC-ODBC Bridge environment.
The JDBC-ODBC Bridge allows access to almost any database, since
the database's ODBC drivers are already available. Type 1 drivers may be
useful for those companies that have an ODBC driver already installed on
client machines.
DisAdvantages
The performance is degraded since the JDBC call goes through the bridge
to the ODBC driver, then to the native database connectivity interface.
The result comes back through the reverse process. Therefore considering
the performance issue, type 1 drivers may not be suitable for large-scale
applications.
The ODBC driver and native connectivity interface must already be
installed on the client machine. Thus any advantage of using Java applets
in an intranet environment is lost, since the deployment problems of
traditional applications.
JDBC driver type 2 -- the native-API/partly Java driver -- converts
JDBC calls into database-specific calls for databases such as SQL Server,
Informix, Oracle, or Sybase. The type 2 driver communicates directly
with the database server; therefore it requires that some binary code be
present on the client machine.
*
Disadvantages
The vendor database library needs to be loaded on each client machine.
Consequently, type 2 drivers cannot be used for the Internet.
Lower performance than type 3 and type 4 drivers.
*
JDBC driver type 3 -- the net-protocol/all-Java driver -- follows a
three-tiered approach whereby the JDBC database requests are passed
through the network to the middle-tier server. The middle-tier server then
translates the request (directly or indirectly) to the database-specific
native-connectivity interface to further the request to the database server.
If the middle-tier server is written in Java, it can use a type 1 or type 2
JDBC driver to do this..
*
The net-protocol/all-Java driver is server-based, so there is no need
for any vendor database library to be present on client machines. Further,
there are many opportunities to optimize portability, performance, and
scalability. Moreover, the net protocol can be designed to make the client
JDBC driver very small and fast to load. Additionally, a type 3 driver
typically provides support for features such as caching (connections,query
results, and so on), load balancing, and advanced system administration
such as logging and auditing
DisAdvantages
Type 3 drivers require database-specific coding to be done in the middle
tier. Additionally, traversing the recordset may take longer, since the
data comes through the backend server.
*
calls into the vendor-specific database management system (DBMS)
protocol so that client applications can communicate directly with the data
base server.
Level 4 drivers are completely implemented in Java to achieve platform
independence and eliminate deployment administration issues.
Network
Advantages
Since type 4 JDBC drivers don't have to translate database requests
to ODBC or a native connectivity interface or to pass the request on to
another server, performance is typically quite good.
The native -protocol/all-Java driver boasts better performance than types
1 and 2.
Also, there's no need to install special software on the client or server.
Further, these drivers can be downloaded dynamically.
Disadvantages
*
It is a database language
It has statements for data definition, query and Update (hence it is a DDL and a DML)
Generally every database SQL language would have one 3rd generation language embedded to increase its problem solving efficiency
SLC - Our People Makes The Difference
*
Structured Query Language (SQL) is the standard language for accessing relational databases. One area of difficulty is that although most DBMSs (DataBase Management Systems) use a standard form of SQL for basic functionality, they do not conform to the more recently-defined standard SQL syntax or semantics for more advanced functionality. For example, not all databases support stored procedures or outer joins, and those that do are not consistent with each other. It is hoped that the portion of SQL that is truly standard will expand to include more and more functionality. In the meantime, however, the JDBC API must support SQL as it is.
One way the JDBC API deals with this problem is to allow any query string to be passed through to an underlying DBMS driver. This means that an application is free to use as much SQL functionality as desired, but it runs the risk of receiving an error on some DBMSs. In fact, an application query need not even be SQL, or it may be a specialized derivative of SQL designed for specific DBMSs (for document or image queries, for example).
*
JDBC Contd.
Jdbc allows the use of SQL statements to interact (create, query and update) with the database
SQL and JAVA syntax necessary to use jdbc effectively
SLC - Our People Makes The Difference
*
1. Jdbc allows the use of SQL statements to interact (create, query and update) with the database .
*
*
*
Driver getDriver()
Enumeration getDrivers()
sun.jdbc.odbc.JdbcOdbcDriver
Using the command Class.forName(“classname_driver”), automatically loads and registers the driver.
SLC - Our People Makes The Difference
*
1. void registerDriver(Driver) :Registers the given driver with the DriverManager. A newly-loaded driver class should call the method registerDriver to make itself known to the DriverManager.
2. void derigesterDriver(Driver):Drops a Driver from the DriverManager's list. Applets can only deregister Drivers from their own classloaders.
3. Connection getConnection(String url):Attempts to establish a connection to the given database URL.
4. getConection(String url,String user,String pwd): Attempts to establish a connection to the given database URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers using the user name and password.
5. Driver getDriver():Attempts to locate a driver that understands the given URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.
6. Enumeration getDrivers():Retrieves an Enumeration with all of the currently loaded JDBC drivers to which the current caller has access.
7. void setLogWriter(PrintWriter) :Sets the logging/tracing PrintWriter object that is used by the DriverManager and all drivers.
8. PrintWriter getLogWriter():Gets the log writer.
* All the methods throws SQLException.
*
*
Driver: This interface that every driver class must implement. The Java SQL framework allows for multiple database drivers. The DriverManager will try to load as many drivers as it can find and then for any given connection request, it will ask each driver in turn to try to connect to the target URL.
1. Connection connect(String, Properties):Attempts to make a database connection to the given URL. The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given URL. The java.util.Properties argument can be used to passed arbitrary string tag/value pairs as connection arguments.
2. boolean acceptsURL(String): Returns true if the driver thinks that it can open a connection to the given URL.
3. int getMajorVersion():Gets the driver's major version number. Initially this should be 1.
4. int getMinorVersion(): Gets the driver's minor version number. Initially this should be 0.
5. boolean jdbcComplient(): Reports whether this driver is a genuine JDBC COMPLIANT driver. A driver may only report true here if it passes the JDBC compliance tests; otherwise it is required to return false. JDBC compliance requires full support for the JDBC API and full support for SQL 92 Entry Level.
6. DriverPropertyInfo getPropertyInfo(String,Properties): Gets information about the possible properties for this driver.
* All the methods throws SQLException.
*
Example
Register a jdbc driver you want to use. Use the getDrivers() method to retrieve a list of registered drivers. Obtain the driverInformation by querying each of the available drivers.
Eg: DriverInfo.java
*
Load the driver by specifying the driver as a string
use the getConnection() method of the DriverManager class to connect to the database
getConnection method
takes a URL as a parameter
URL (a String) specifies the type of protocol/subprotocol jdbc will use to connect to the database)
returns a Connection object
*
The standard way to establish a connection with a database is to call the method DriverManager.getConnection.
This method takes a string containing a URL. The DriverManager class attempts to locate a driver than can connect to the database represented by that URL.
The DriverManager class maintains a list of registered Driver classes, and when the method getConnection is called, it checks with each driver in the list until it finds one that can connect to the database specified in the URL.
*
*
The following code exemplifies opening a connection to a database located at the URL "jdbc:odbc:datasource" with a user ID of
”scott" and ”tiger" as the password :
String url = "jdbc:odbc:datasource”;
*
net protocol should have port number/ host name
JDBC:ODBC bridge should use the simple protocol
SLC - Our People Makes The Difference
*
A JDBC URL provides a way of identifying a database so that the appropriate driver will recognize it and establish a connection with it.
Naming should include connection information :
1. Net protocol should have port number/ host name.
2. JDBC:ODBC bride should use the simple protocol.
*
jdbc:<subprotocol name>:<sub name>
subprotocol: the database connectivity mechanism supported by the driver.
subname: specify network address of db server (URL for n/w address //Hostname:port/subname)
Example:
jdbc:odbc:javatmp
jdbc:dbnet://HMANT001:1526/ordb
“javatmp” is an odbc source name
Connect using dbnet protocol to hmant001 at port 1526 with ordbc as connection name
SLC - Our People Makes The Difference
*
The three parts of a JDBC URL are broken down as follows:
1. jdbc-the protocol. The protocol in a JDBC URL is always jdbc.
2. <subprotocol>-the name of the driver or the name of a database connectivity mechanism, which may be supported by one or more drivers. A prominent example of a subprotocol name is "odbc", which has been reserved for URLs that specify ODBC-style data source names. For example, to access a database through a JDBC-ODBC bridge, one might use a URL such as the following: jdbc:odbc:fred
In this example, the subprotocol is "odbc", and the subname "fred" is a local
ODBC data source.
If one wants to use a network name service (so that the database name in the JDBC URL does not have to be its actual name), the naming service can be the subprotocol. So, for example, one might have a URL like:
jdbc:dcenaming:accounts-payable
*
subprotocol
*
3. <subname>-a way to identify the database. The subname can vary, depending on the subprotocol, and it can have a subsubname with any internal syntax the driver writer chooses. The point of a subname is to give enough information to locate the database. In the previous example, "fred" is enough because ODBC provides the remainder of the information. A database on a remote server requires more information, however. If the database is to be accessed over the Internet, for example, the network address should be included in the JDBC URL as part of the subname and should follow the standard URL naming convention of
//hostname:port/subsubname
Supposing that "dbnet" is a protocol for connecting to a host on the Internet, a
JDBC URL might look like this:
jdbc:dbnet://wombat:356/fred
*
Connection: A connection (session) with a specific database. Within the context of a Connection, SQL statements are executed and results are returned.
A Connection's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.
1.Stmt createStatement(): Creates a Statement object for sending SQL statements to the database.
2.Stmt createStatement(int,int): Creates a Statement object that will generate ResultSet objects with the given type and concurrency.
3. CallableStmt preparecall(String):Creates a CallableStatement object for calling database stored procedures. The CallableStatement object provides methods for setting up its IN and OUT parameters, and methods for executing the call to a stored procedure.
4.PrepareStmt prepareStatement(String):Creates a PreparedStatement object for sending parameterized SQL statements to the database. A SQL statement with or without IN parameters can be pre-compiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.
Contd.….
Register and load the jdbc-odbc driver.
Connect to the database using getConnection(“data source url “);
If there is an exception thrown during the connection display info and exit
Eg1: CheckConnect.java
Eg2: ConnectType4.java
*
5. void rollback():Drops all changes made since the previous commit/rollback and releases any database locks currently held by this Connection. This method should be used only when auto- commit has been disabled.
6. void commit(): Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by the Connection. This method should be used only when auto-commit mode has been disabled.
7. set/getAutoCommit(boolean):Used for setting and getting the mode of committing the transactions.
8. DatabaseMetaData getMetaData(): Gets the metadata regarding this connection's database. A Connection's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is made available through a DatabaseMetaData object.
9. void close(): Releases a Connection's database and JDBC resources immediately instead of waiting for them to be automatically released.
*
Connect to the database using getConnection(String, Properties); or getConnection(String,String,String)
If there is an exception thrown during the connection display info and exit
Eg: CheckConnect2.java
*
*
Create new instance of jdbc-odbc driver.
Connect to database using the connect(String, Properties) method in the driver class
If there is an exception thrown during the connection display info and exit
Eg: CheckConnect3.java
*
*
More methods are avaialable
*
5.String getDriverName(): Gives what's the name of this JDBC driver.
6.String getDriverVersion(): Gives what's the Version of this JDBC driver?
7.String getNumericFunctions(): Gets a comma-separated list of math functions. These are the X/Open CLI math function names used in the JDBC function escape clause.
8.String getSystemFunctions(): Gets a comma-separated list of system functions. These are the X/Open CLI system function names used in the JDBC function escape clause.
9.String getStringFunctions(): Gets a comma-separated list of string functions. These are the X/Open CLI string function names used in the JDBC function escape clause.
* All the method throws SQLException.
*
Connect to database
Display information about the Database
Eg: DatabaseInfo.java
*
*
*
*
Retrieving Data from a DB
To retrieve data one must use one of the following classes to query the database (after connection has been established)
Statement
PreparedStatement
CallableStatement
A Statement object is returned from the createStatement() method of Connection interface
SLC - Our People Makes The Difference
*
To retrieve data one must use one of the following classes to query the
database (after connection has been established) :
1. Statement
2. PreparedStatement
3. CallableStatement
*
Method createStatement() of Connection interface returns handle to Statement
To see the information in rows sent from the database, we need to use methods in the ResultSet interface
SLC - Our People Makes The Difference
*
Statement: The object used for executing a static SQL statement and obtaining the
results produced by it. Only one ResultSet object per Statement object can be open at any point in time.
1.ResultSet executeQuery(String sql): Executes an SQL statement that returns a single ResultSet object. Returns: a ResultSet object that contains the data produced by the given query; never null.
2.int executeUpdate(String): Executes an SQL INSERT, UPDATE or DELETE statement. In addition, SQL statements that return nothing, such as SQL DDL statements, can be executed.Returns: either the row count for INSERT, UPDATE or DELETE statements, or 0 for SQL statements that return nothing.
3.boolean execute(sql): Executes an SQL statement that may return multiple results. Returns: true if the next result is a ResultSet object; false if it is an update count or there are no more results.
4.void close(): Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. It is generally good practice to release resources as soon as you are finished with them to avoid tying up database resources.
5.ResultSet getResultSet():Returns the current result as a ResultSet object. This method should be called only once per result.
6.void clearWarnings(): Clears all the warnings reported on this Statement object.
* All the methods throws SQLException.
*
public
methods
To find out the number of columns and column types we need to use the ResultSetMetaData interface
String argument implies a column name
int argument implies a column position (count is from 1 onwards)
SLC - Our People Makes The Difference
*
ResultSet: A table of data representing a database result set, which is usually
generated by executing a statement that queries the database.
1.int findColumn(String colname): Maps the given ResultSet column name to its ResultSet column index.
2. Boolean getBoolean(int/String):Gets the value of the designated column in the current row of this ResultSet object as a boolean in the Java programming language.
3.get methods available for all primary datatypes .
4.void close(): Releases this ResultSet object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.
5. ResultSetMetaData getMetaData():Retrieves the number, types and properties of this ResultSet object's columns.
6. Boolean next():Moves the cursor down one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
7. Boolean previous():Moves the cursor to the previous row in this ResultSet object.
8. Boolean wasNull():Reports whether the last column read had a value of SQL NULL.
* All methods throws SQLException.
*
ResultSetMetaData:An object that can be used to get information about the types and properties of the columns in a ResultSet object.
1.int getColumnCount():Returns the number of columns in this ResultSet object.
2.String getColumnDisplaySize(int col):Gets the designated column's suggested title for use in printouts and displays.
3.String getColumnLabel(int col):Get the designated column's name.
4.String getColumnName(int col): Get the designated column's name.
5.int getColumnType(int col):Retrieves the designated column's SQL type. Returns: SQL type from java.sql.Types
6.String getColumnTypeName(int col):Retrieves the designated column's database-specific type name. Returns:type name used by the database.
7.boolean isReadOnly(int col):Indicates whether the designated column is definitely not writable.
8.boolean isSearchable(int col): Indicates whether the designated column can be used in a where clause.
9.boolean isWritable(int col):Indicates whether it is possible for a write on the designated column to succeed.
10.String getTableName(int col):Gets the designated column's table name.
* All methods throw SQLException.
Connect to database
get a handle to a statement, and call executeQuery(…) in the statement
get the count of columns from the MetaData information
display the information rowwise (Note all info is being displayed as a String)
Eg: SQLQuery.java
*
*
*
*
Connect to database
Get a handle to a statement, and call executeQuery(…) in the statement
Get the count of columns from the MetaData information
Display the column information of table
Eg: SQLQueryTableInfo.java
*
*
Data / Objects
SQL defines its data types. Hence while java retrieves these data types, one must known the type conversion between the two.
SLC - Our People Makes The Difference
*
Since SQL data types and Java data types are not identical, there needs to be some mechanism for reading and writing data between an application using Java types and a database using SQL types.
JDBC defines a standard mapping from the JDBC database types to Java types. For example, a JDBC INTEGER is normally mapped to a Java int. This supports a simple interface for reading and writing JDBC values as simple Java types.
*
*
1. CHAR String
2. VARCHAR String
3. LONGVARCHAR String
4. NUMERIC java.math.BigDecimal
5. DECIMAL java.math.BigDecimal
6. BIT boolean
7. TINYINT int
8. SMALLINT int
9. INTEGER int
10. BIGINT long
11. REAL float
12. FLOAT double
13. DOUBLE double
14. BINARY byte[]
15. DATE java.sql.Date
16. TIME java.sql.Time
17. TIMESTAMP java.sql.Timestamp
Data Conversion in ResultSets
getXXX(i) will attempt to convert the SQL Data type of column “i” into whatever type getXXX() method returns
Example
let the first column in the Result set be an ID number (SQL TYPE: INTEGER)
if we use getString(1), it converts the INTEGER of SQL into a String object, and it returns a handle to this object
Hence to return an integer, one must use getInt (1) which returns an int
SLC - Our People Makes The Difference
*
Data Conversion in ResultSet
getXXX(i) will attempt to convert the SQL Data type of column “i” into
whatever type getXXX() method returns.
Example :
Let the first column in the Result set be an ID number (SQL TYPE: INTEGER).
if we use getString(1), it converts the INTEGER of SQL into a String object, and it returns a handle to this object
Hence to return an integer, one must use getInt (1) which returns an
int .
Step 1: read the value using getXXX().
Setup 2: use the wasNull() method of the Result set class. If it returns true the value just read was a SQL Null value
it getXXX() would return zero for SQL nulls for int, byte, long ……
SLC - Our People Makes The Difference
*
To determine if a given result value is JDBC NULL, one must first read the column and then use the ResultSet.wasNull method to discover if the read returned a JDBC NULL.
When one has read a JDBC NULL using one of the ResultSet.getXXX methods, the method wasNull will return one of the following:
* A Java null value for those getXXX methods that return Java objects
(methods such as getString, getBigDecimal, getBytes, getDate, getTime,
getTimestamp, getAsciiStream, getUnicodeStream, getBinaryStream,
getObject).
* A zero value for getByte, getShort, getInt, getLong, getFloat, and getDouble.
* A false value for getBoolean.
*
Passing Parameters to SQL Statements
To retrieve a row based on a value, one cannot use the following query string
“select empid, name from employees where empid=3”
the problem with the above statement is that the empid is having value string “3” and not int 3.
Solution: Use PrepareStatement instead of the Statement class
SLC - Our People Makes The Difference
*
one cannot use the following query string:
“select empid, name from employees where empid=3”
The problem with the above statement is that the empid is having value string “3” and not int 3.
Solution: Use PrepareStatement instead of the Statement class
*
- Statement. addBatch(“SQL Query);
Step 2 : execute Batch
Eg. : BatchUpdate.java
public
methods
The string to be queried must be passed to “prepareStatement” of Connection class as a parameter.
setxxx() methods in this interface do not do conversions, but insert the corresponding java to SQL mapped data types
SLC - Our People Makes The Difference
*
PrepareStatement:An object that represents a precompiled SQL statement.
A SQL statement is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.
1.ResultSet executeQuery(): Executes the SQL query in this PreparedStatement object and returns the result set generated by the query.Returns: a ResultSet object that contains the data produced by the query; never null.
2.int executeUpdate(): Executes the SQL INSERT, UPDATE or DELETE statement in this PreparedStatement object. In addition, SQL statements that return nothing, such as SQL DDL statements, can be executed.Returns: either the row count for INSERT, UPDATE or DELETE statements; or 0 for SQL statements that return nothing.
3.boolean execute(): Executes any kind of SQL statement. Some prepared statements return multiple results; the execute method handles these complex statements as well as the simpler form of statements handled by the methods executeQuery and executeUpdate.
4.ResultSet getResultSet():Inherited from Statement interface.
5.void clearParameters(): Clears the current parameter values immediately.
*
PreparedStatement ps = conn.prepareStatement(“select empid, empname, empdesc form employees where empid=?”);
ps.setInt(1,3);
ps.executeQuery();
In parameters in the query string are filled with “?” marks.
Use setXXX(1, val) to set the first parameter with val of type XXX
Use setXXX(2, …) to insert at the second question mark
SLC - Our People Makes The Difference
*
PreparedStatement ps = conn.prepareStatement(“select empid,
empname, empdesc form employees where empid=?”);
2. ps.setInt(1,3);
3. ps.executeQuery();
Connect to database
Display information about the person with employeeID = 3 from employees table in “Northwind” database.
Eg: SQLQuery2.java
*
*
ProjectID - integer
ProjectName - text
ProjectLocation - text
ProjectStartDate - Date
*
*
JDBC ver 1.0
To send an SQL null as parameter use the setNull(int,int) in the PreparedStatement interface
first integer is the position of the parameter
second integer is the constant for SQLtype of parameter
constants defined in java.sql.Types.xxx
SLC - Our People Makes The Difference
*
Sending SQL nulls as parameters
To send an SQL null as parameter use the setNull(int,int) in the PreparedStatement interface .
* first integer is the position of the parameter
* second integer is the constant for SQLtype of parameter
Constants defined in java.sql.Types.xxx :
Exercise
Insert the value into the table Projects created in the previous exercise .
(4, Cold Fusion, , “1999-09-9”)
*
*
Stored Procedures
To execute a stored procedure call, one must use the CallableStatement interface
This can be created using the prepareCall(String) method of the Connection interface
A stored procedure call might return some values
to retrieve them, you need to register the out parameter types before executing the stored procedure query
CallableStatement extends from PreparedStatement interface
SLC - Our People Makes The Difference
*
A CallableStatement object provides a way to call stored procedures in a standard way for all DBMSs. The syntax for a procedure that returns a result parameter is:
{? = call procedure_name[(?, ?, ...)]}
The syntax for a stored procedure with no parameters would look like this:
{call procedure_name}
CallableStatement cstmt = con.prepareCall("{call getTestData(?, ?)}");
CallableStatement inherits Statement methods, which deal with SQL statements in general, and it also inherits PreparedStatement methods, which deal with IN parameters. All of the methods defined in CallableStatement deal with OUT parameters or the output aspect of INOUTparameters: registering the JDBC types (generic SQL types) of the OUT parameters, retrieving values from them, or checking whether a returned value was JDBC NULL.
*
stmt.registerOutParameter(1,Types.TINYINT);
stmt.registerOutParameter(2,Types.DOUBLE);
*
stmt.registerOutParameter(1,Types.TINYINT);
stmt.registerOutParameter(2,Types.DOUBLE);
*
*
+ "select * FROM emp;”
Statement stmt = conn.createStatement();
SLC - Our People Makes The Difference
*
1. String createProcedure = "create procedure SHOWEMP " + "as "
+ "select * FROM emp;”
SLC - Our People Makes The Difference
*
CallableStatement stmt =conn.prepareCall(“{call SHOWEMP}”);
ResultSet rs = stmt.executeQuery();
Exercise (contd…)

Recommended