apache > db
Apache DB Project
 
Font size:      

Connections

Connections

A Connection object represents a connection with a database. Within the scope of one Connection, you access only a single Derby database. (Database-side JDBC procedures can allow you to access more than one database in some circumstances.) Depending on your Derby product license, a single application might allow one or more Connections to Derby, either to a single database or to many different databases, provided that all the databases are within the same system (see Derby System).

With DriverManager, you use the connection URL as an argument to get the getConnection method to specify which database to connect to and other details (see Derby JDBC Database Connection URL).

The following example shows an application establishing three separate connections to two different databases in the current system.

Connection conn = DriverManager.getConnection(
    "jdbc:derby:sample");
System.out.println("Connected to database sample");
conn.setAutoCommit(false);
Connection conn2 = DriverManager.getConnection(
    "jdbc:derby:newDB;create=true");
System.out.println("Created AND connected to newDB");
conn2.setAutoCommit(false);
Connection conn3 = DriverManager.getConnection(
    "jdbc:derby:newDB");
System.out.println("Got second connection to newDB");
conn3.setAutoCommit(false);

A Connection object has no association with any specific thread; during its lifetime, any number of threads might have access to it, as controlled by the application.

Statements

To execute SQL statements against a database, an application uses Statements (java.sql.Statement) and PreparedStatements (java.sql.PreparedStatement), or CallableStatements (java.sql.CallableStatement) for stored procedures. Because PreparedStatement extends Statement and CallableStatement extendsPreparedStatement, this section refers to both as Statements. Statements are obtained from and are associated with a particular Connection.

ResultSets and Cursors

Executing a Statement that returns values gives a ResultSet (java.sql.ResultSet), allowing the application to obtain the results of the statement. Only one ResultSet can be open for a particular Statement at any time, as per the JDBC specification.

Thus, executing a Statement automatically closes any open ResultSet generated by an earlier execution of that Statement.

For this reason, you must use a different Statement to update a cursor (a named ResultSet) from the one used to generate the cursor.

The names of open cursors must be unique within a Connection. For more information about how to use cursors and ResultSets, see SQL and JDBC ResultSet/Cursor Mechanisms.

Nested Connections

SQL statements can include routine invocations. If these routines interact with the database, they must use a Connection.

For more information, see Programming Database-Side JDBC Procedures.


Previous Page
Next Page
Table of Contents
Index