Java Database Connectivity: Difference between revisions

Content deleted Content added
definition
 
(570 intermediate revisions by more than 100 users not shown)
Line 1:
{{Short description|API for Java}}
'''JDBC''' is an [[Application programming interface|API]] for the [[Java programming language]] that defines how a client may access a [[database]]. It provides methods for querying and updating data in a database. JDBC is oriented towards [[Relational database management system|relational databases]].
'''Java Database Connectivity''' ('''JDBC''') is an [[application programming interface]] (API) for the [[Java (programming language)|Java]] programming language which defines how a client may access a [[database]]. It is a Java-based data access technology used for Java database connectivity. It is part of the [[Java Standard Edition]] platform, from [[Oracle Corporation]]. It provides methods to query and update data in a database, and is oriented toward [[Relational database|relational databases]]. A JDBC-to-[[ODBC]] bridge enables connections to any ODBC-accessible data source in the [[Java virtual machine]] (JVM) host environment.{{Infobox software
|name = JDBC
|logo =
|caption =
|developer = Oracle Corporation
|latest release version = JDBC 4.3
|latest release date = {{Start date|2017|09|21}}
|latest preview version =
|latest preview date =
|operating system = [[Cross-platform]]
|genre = Data access API
|license =
|website = {{Javadoc:SE-guide|jdbc|JDBC API Guide}}
}}
 
==History and implementation==
The [[Java Platform, Standard Edition]] includes the JDBC API together with an [[Open database connectivity|ODBC]] implementation of the API enabling connections to any relational database that supports [[Open database connectivity|ODBC]]. This driver is [[native code]] and not Java, and is [[closed source]].[http://java.sun.com/products/jdbc/jdbc-3_0-fr-spec-license.html]
[[Sun Microsystems]] released JDBC as part of [[Java Development Kit]] (JDK) 1.1 on February 19, 1997.<ref name="JDK 1.1 release">
{{cite web
| title = Sun Ships JDK 1.1 -- Javabeans Included
| date = 1997-02-19
| work = www.sun.com
| publisher = [[Sun Microsystems]]
| url = http://www.sun.com/smi/Press/sunflash/1997-02/sunflash.970219.0001.xml
| archive-url = https://web.archive.org/web/20080210044125/http://www.sun.com/smi/Press/sunflash/1997-02/sunflash.970219.0001.xml
| url-status = dead
| archive-date =2008-02-10
| access-date = 2010-02-15
| quote = February 19, 1997 - The JDK 1.1 [...] is now available [...]. This release of the JDK includes: [...] Robust new features including JDBC for database connectivity
}}
</ref>
Since then it has been part of the [[Java Platform, Standard Edition]] (Java SE).
 
The JDBC classes are contained in the [[Java package]] {{Javadoc:SE|package=java.sql|java/sql|module=java.sql}} and {{Javadoc:SE|package=javax.sql|javax/sql|module=java.sql}}, as well as a few other classes elsewhere. Everything involved in JDBC is exported through [[Java Platform Module System|module]] <code>java.sql</code>.
== Overview ==
 
JDBC has been part of the Java Standard Edition since the release of JDK 1.1. The JDBC classes are contained in the [[Java package]] {{Javadoc:SE|package=java.sql|java/sql}}. Starting with version 3.01, JDBC has been developed under the [[Java Community Process]]. JSR 54 specifies JDBC 3.0 (included in J2SE 1.34), JSR 114 specifies the JDBC Rowset additions, and JSR 221 is the specification of JDBC 4.0 (included in Java SE 6).<ref>[http://java.sun.com/products/jdbc/download.html#corespec40 JDBC API Specification Version: 4.0].</ref>
 
JDBC 4.1, is specified by a maintenance release 1 of JSR 221<ref>{{cite web|url=http://jcp.org/aboutJava/communityprocess/mrel/jsr221/index.html|title=The Java Community Process(SM) Program - communityprocess - mrel|website=jcp.org|access-date=22 March 2018}}</ref> and is included in Java SE 7.<ref>{{cite web|url=http://docs.oracle.com/javase/7/docs/technotes/guides/jdbc/jdbc_41.html|title=JDBC 4.1|website=docs.oracle.com|access-date=22 March 2018}}</ref>
JDBC allows multiple implementations to exist and be used by the same application. The API provides a mechanism for dynamically loading the correct Java packages and registering them with the JDBC Driver Manager. The Driver Manager is used as a connection factory for creating JDBC connections.
 
JDBC 4.2, is specified by a maintenance release 2 of JSR 221<ref>{{cite web|url=https://jcp.org/aboutJava/communityprocess/mrel/jsr221/index2.html|title=The Java Community Process(SM) Program - communityprocess - mrel|website=jcp.org|access-date=22 March 2018}}</ref> and is included in Java SE 8.<ref>{{cite web|url=http://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/jdbc_42.html|title=JDBC 4.2|website=docs.oracle.com|access-date=22 March 2018}}</ref>
JDBC connections support creating and executing statements. These statements may be update statements such as [[SQL]] INSERT, UPDATE and DELETE or they may be query statements using the SELECT statement. Additionally, stored procedures may be invoked through a statement. Statements are one of the following types:
 
The latest version, JDBC 4.3, is specified by a maintenance release 3 of JSR 221<ref>{{cite web|url=https://jcp.org/aboutJava/communityprocess/mrel/jsr221/index3.html|title=The Java Community Process(SM) Program - communityprocess - mrel|website=jcp.org|access-date=22 March 2018}}</ref> and is included in Java SE 9.<ref>{{cite web|url=http://docs.oracle.com/javase/9/docs/api/java/sql/package-summary.html|title=java.sql (Java SE 9 & JDK 9)|website=docs.oracle.com|access-date=22 March 2018}}</ref>
* {{Javadoc:SE|java/sql|Statement}} &ndash; the statement is sent to the database server each and every time.
* {{Javadoc:SE|java/sql|PreparedStatement}} &ndash; the statement is cached and then the execution path is pre determined on the database server allowing it to be executed multiple times in an efficient manner.
* {{Javadoc:SE|java/sql|CallableStatement}} &ndash; used for executing stored procedures on the database.
 
{| class="wikitable"
Update statements such as INSERT, UPDATE and DELETE return an update count that indicates how many rows were affected in the database. These statements do not return any other information.
|+ JDBC versions
|-
! JDBC version !! Java version !! Release Type !! Release date
|-
| 1.1 || JDK 1.1 || Main || 1997-02-19.<ref name="JDK 1.1 release" />
|-
| [https://www.jcp.org/en/jsr/detail?id=54 3.0] || J2SE 1.4 || Main || 2002-05-09
|-
| [https://www.jcp.org/en/jsr/detail?id=221 4.0] || Java SE 6 || Main || 2006-12-11
|-
| [https://www.jcp.org/en/jsr/detail?id=221 4.1] || Java SE 7 || Maintenance || 2011-10-13
|-
| [https://www.jcp.org/en/jsr/detail?id=221 4.2] || Java SE 8 || Maintenance || 2014-03-04
|-
| [https://www.jcp.org/en/jsr/detail?id=221 4.3] || Java SE 9 || Maintenance || 2017-09-21
|}
 
==Functionality==
Query statements return a JDBC row result set. The row result set is used to walk over the result set. Individual columns in a row are retrieved either by name or by column number. There may be any number of rows in the result set. The row result set has metadata that describes the names of the columns and their types.
{| class="wikitable floatright"
|+ Host database types which Java can convert to with a function
|-
! Oracle Datatype
! <code>setXXX()</code> Methods
|-
| CHAR
| <code>setString()</code>
|-
| VARCHAR2
| <code>setString()</code>
|-
|rowspan="8"| NUMBER
| <code>setBigDecimal()</code>
|-
| <code>setBoolean()</code>
|-
| <code>setByte()</code>
|-
| <code>setShort()</code>
|-
| <code>setInt()</code>
|-
| <code>setLong()</code>
|-
| <code>setFloat()</code>
|-
| <code>setDouble()</code>
|-
| INTEGER
| <code>setInt()</code>
|-
| FLOAT
| <code>setDouble()</code>
|-
| CLOB
| <code>setClob()</code>
|-
| BLOB
| <code>setBlob()</code>
|-
| RAW
| <code>setBytes()</code>
|-
| LONGRAW
| <code>setBytes()</code>
|-
|rowspan="3"| DATE
| <code>setDate()</code>
|-
| <code>setTime()</code>
|-
| <code>setTimestamp()</code>
|}
 
Since JDBC is mostly a collection of interface definitions and specifications, it allows multiple implementations of these interfaces to exist and be used by the same application at runtime. The API provides a mechanism for dynamically loading the correct Java packages and registering them with the JDBC Driver Manager ({{code|DriverManager}}). {{code|DriverManager}} is used as a {{java|Connection}} [[Factory (object-oriented programming)|factory]] for creating JDBC connections.
There is an extension to the basic JDBC API in the {{Javadoc:SE|package=javax.sql|javax/sql}} package that allows for scrollable result sets and cursor support among other things.
 
JDBC connections support creating and executing statements. JDBC connections support update statements such as SQL's [[Create (SQL)|CREATE]], [[Insert (SQL)|INSERT]], [[Update (SQL)|UPDATE]] and [[Delete (SQL)|DELETE]], or query statements such as [[Select (SQL)|SELECT]]. Additionally, stored procedures may be invoked through a JDBC connection. JDBC represents statements using one of the following classes:
== Example ==
* {{Javadoc:SE|java/sql|Statement|module=java.sql}} &ndash; the {{java|Statement}} is sent to the database server each and every time. In other words, the {{java|Statement}} methods are executed using SQL statements to obtain a {{code|ResultSet}} object containing the data.{{sfn | Bai | 2022 | p=74}}
* {{Javadoc:SE|java/sql|PreparedStatement|module=java.sql}} &ndash; {{code|PreparedStatement}} is a subinterface of the {{code|Statement}} interface.{{sfn | Bai | 2022 | p=74}} The statement is cached and then the [[Query plan|execution path]] is pre-determined on the database server, allowing it to be executed multiple times in an efficient manner.{{sfn | Bai | 2022 | p=74}} {{code|PreparedStatement}} is used to execute pre-compiled SQL statements.{{sfn | Bai | 2022 | p=74}} Running pre-compiled statements increases statement execution efficiency and performance. The {{code|PreparedStatement}} is often used for dynamic statement where some input parameters must be passed into the target database.{{sfn | Bai | 2022 | loc=§4.2.3.5 More About the Execution Methods | pp=122-124}} The
{{code|PreparedStatement}} allows the dynamic query to vary depending on the query parameter.{{sfn | Bai | 2022 | loc= §3.2 JDBC Components and Architecture | pp=72-74}}
* {{Javadoc:SE|java/sql|CallableStatement|module=java.sql}} &ndash; {{code|CallableStatement}} is a subinterface of the {{code|Statement}} interface.{{sfn | Bai | 2022 | loc= §3.2 JDBC Components and Architecture | pp=72-74}} It is used for executing [[stored procedures]] on the database.{{sfn | Bai | 2022 | loc= §3.2 JDBC Components and Architecture | pp=72-74}}{{sfn | Horstmann | 2022 | loc=§5.5.3 SQL Escapes}} Both input and output parameters must be passed into the database for stored procedures.{{sfn | Bai | 2022 | loc= §4.2.3.5 JDBC Components and Architecture | pp=122-124}}
 
Update statements such as INSERT, UPDATE and DELETE return an update count indicating the number of [[Row (database)|rows]] affected in the database as an integer.{{sfn | Bai | 2022 | loc= §4.2.3.5 JDBC Components and Architecture | pp=122-124}} These statements do not return any other information.
The method {{Javadoc:SE|member=forName(String)|java/lang|Class|forName(java.lang.String)}} is used to load the JDBC driver class. The line below causes the JDBC driver from ''some jdbc vendor'' to be loaded into the application.
 
Query statements return a JDBC row result set. The row result set is used to walk over the [[result set]]. Individual [[Column (database)|columns]] in a row are retrieved either by name or by column number. There may be any number of rows in the result set. The row result set has metadata that describes the names of the columns and their types.
Class.forName( "com.somejdbcvendor.TheirJdbcDriver" );
 
There is an extension to the basic JDBC API in the {{Javadoc|module=java.sql|package=javax.sql|monotype=y}}.
When a {{Javadoc:SE|java/sql|Driver}} class is loaded, it creates an instance of itself and registers it with the {{Javadoc:SE|java/sql|DriverManager}}. This can be done by including the needed code in the driver class's <code>static</code> block. e.g. <code>DriverManager.registerDriver(Driver driver)</code>
 
JDBC connections are often managed via a [[connection pool]] rather than obtained directly from the driver.{{sfn | Bai | 2022 | loc=§3.5.1 JDBC DataSource | p=83}}
Now when a connection is needed, one of the <code>DriverManager.getConnection()</code> methods is used to create a JDBC connection.
 
==Examples==
Connection conn = DriverManager.getConnection(
"jdbc:somejdbcvendor:other data needed by some jdbc vendor",
"myLogin",
"myPassword" );
 
When a Java application needs a database connection, one of the <code>DriverManager.getConnection()</code> methods is used to create a JDBC {{java|Connection}}. The URL used is dependent upon the particular database and JDBC driver. It will always begin with the "jdbc:" protocol, but the rest is uptoup to the particular vendor. Once a connection is established, a statement must be created.
 
<syntaxhighlight lang="java">
Statement stmt = conn.createStatement();
Connection conn = DriverManager.getConnection(
stmt.executeUpdate( "INSERT INTO MyTable( name ) VALUES ( 'my name' ) " );
"jdbc:somejdbcvendor:other data needed by some jdbc vendor",
"myLogin",
"myPassword");
try {
/* you use the connection here */
} finally {
//It's important to close the connection when you are done with it
try {
conn.close();
} catch (Throwable e) { /* Propagate the original exception
instead of this one that you want just logged */
logger.warn("Could not close JDBC Connection", e);
}
}
</syntaxhighlight>
 
Starting from Java SE 7 you can use Java's [http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html try-with-resources] statement to simplify the above code:
Data is retrieved from the database using a database query mechanism. The example below shows creating a statement and executing a query.
<syntaxhighlight lang="java">
try (Connection conn = DriverManager.getConnection(
"jdbc:somejdbcvendor:other data needed by some jdbc vendor",
"myLogin",
"myPassword")) {
/* you use the connection here */
} // the VM will take care of closing the connection
</syntaxhighlight>
 
Once a connection is established, a {{java|Statement}} can be created.
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM MyTable" );
while ( rs.next() ) {
int numColumns = rs.getMetaData().getColumnCount();
for ( int i = 1 ; i <= numColumns ; i++ ) {
//Column numbers start at 1.
//Also there are many methods on the result set to return
// the column as a particular type. Refer to the Sun documentation
// for the list of valid conversions.
System.out.println( "COLUMN " + i + " = " + rs.getObject(i) );
}
}
rs.close();
stmt.close();
 
<syntaxhighlight lang="java">
Typically, however, it would be rare for a seasoned Java programmer to code in such a fashion. The usual practice would be to abstract the database logic into an entirely different class and to pass preprocessed strings (perhaps derived themselves from a further abstracted class) containing SQL statements and the connection to the required methods. Abstracting the data model from the application code makes it more likely that changes to the application and data model can be made independently.
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("INSERT INTO MyTable(name) VALUES ('my name')");
}
</syntaxhighlight>
 
Note that {{java|Connection}}s, {{java|Statement}}s, and {{java|ResultSet}}s often tie up [[operating system]] resources such as sockets or [[file descriptor]]s. In the case of {{java|Connection}}s to remote database servers, further resources are tied up on the server, e.g. [[Cursor (databases)|cursors]] for currently open {{java|ResultSet}}s.
An example of a <code>PreparedStatement</code> query. Using <code>conn</code> and class from first example.
It is vital to <code>close()</code> any JDBC object as soon as it has played its part;
[[Garbage collection (computer science)|garbage collection]] should not be relied upon.
The above try-with-resources construct is a code pattern that obviates this.
 
Data is retrieved from the database using a database query mechanism. The example below shows creating a statement and executing a query.
PreparedStatement ps = null;
ResultSet rs = null;
ps = conn.prepareStatement( "SELECT i.*, j.* FROM Omega i, Zappa j"
+ "WHERE i = ? AND j = ?" );
try {
// In the prepared statement ps, the question mark denotes variable input,
// which can be passed through a parameter list, for example.
// The following replaces the question marks,
// with the string or int, before sending it to SQL.
// The first parameter corresponds to the nth occurrence of the ?,
// the second parameter tells Java to replace it with
// the second item.
ps.setString(1, "Poor Yorick");
ps.setInt(2, 8008);
// The ResultSet rs, receives the SQL Query response.
rs = ps.executeQuery();
try {
while ( rs.next() ) {
int numColumns = rs.getMetaData().getColumnCount();
for ( int i = 1 ; i <= numColumns ; i++ ) {
//Column numbers start at 1.
//Also there are many methods on the result set to return
// the column as a particular type. Refer to the Sun documentation
// for the list of valid conversions.
System.out.println( "COLUMN " + i + " = " + rs.getObject(i) );
} // for
} // while
} catch( SQLException e ) { // some error handling
} finally {
try { rs.close(); } catch( SQLException se ) { /* handle errors here or ignore them */ }
}
} catch (SQLException e) { // typical exception handling here
} finally { // note that these resources need to be closed in the finally clause to avoid
// a resource leak since it should always be called
try { ps.close; } catch( SQLException e){ /* handle errors here or ignore them */ }
} // try
 
<syntaxhighlight lang="java">
'''Here are examples of host database types, Java can convert to with a function'''.&nbsp;
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM MyTable")
) {
while (rs.next()) {
int numColumns = rs.getMetaData().getColumnCount();
for (int i = 1; i <= numColumns; i++) {
// Column numbers start at 1.
// Also, there are many methods on the result set to return
// the column as a particular type. Refer to the Sun documentation
// for the list of valid conversions.
System.out.println( "COLUMN " + i + " = " + rs.getObject(i));
}
}
}
</syntaxhighlight>
 
The following code is an example of a <code>PreparedStatement</code> query which uses <code>conn</code> and class from the first example:
<table BORDER CELLSPACING=0 CELLPADDING=3 >
<tt><font size=+1>setXXX()</font></tt>
Methods
 
<syntaxhighlight lang="java">
<tr class="FormalW">
try (PreparedStatement ps =
<th ALIGN=LEFT VALIGN=TOP class="FormalW"><b><font face="Arial, Helvetica, sans-serif">Oracle
conn.prepareStatement("SELECT i.*, j.* FROM Omega i, Zappa j WHERE i.name = ? AND j.num = ?")
Datatype</font></b></th>
) {
// In the SQL statement being prepared, each question mark is a placeholder
// that must be replaced with a value you provide through a "set" method invocation.
// The following two method calls replace the two placeholders; the first is
// replaced by a string value, and the second by an integer value.
ps.setString(1, "Poor Yorick");
ps.setInt(2, 8008);
 
// The ResultSet, rs, conveys the result of executing the SQL statement.
<th ALIGN=LEFT VALIGN=BOTTOM class="FormalW">'''<font face="Arial, Helvetica, sans-serif">setXXX()</font>'''</th>
// Each time you call rs.next(), an internal row pointer, or cursor,
</tr>
// is advanced to the next row of the result. The cursor initially is
// positioned before the first row.
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
int numColumns = rs.getMetaData().getColumnCount();
for (int i = 1; i <= numColumns; i++) {
// Column numbers start at 1.
// Also, there are many methods on the result set to return
// the column as a particular type. Refer to the Sun documentation
// for the list of valid conversions.
System.out.println("COLUMN " + i + " = " + rs.getObject(i));
} // for
} // while
} // try
} // try
</syntaxhighlight>
 
If a database operation fails, JDBC raises an {{Javadoc:SE|java/sql|SQLException|module=java.sql}}. There is typically very little one can do to recover from such an error, apart from logging it with as much detail as possible. It is recommended that the {{code|SQLException}} be translated into an application ___domain exception (an unchecked one) that eventually results in a transaction rollback and a notification to the user.
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
<td class="FormalW">
<div class="TB">CHAR&nbsp;</div>
</td>
 
The following code is an example of a [[database transaction]]:
<td class="FormalW">
<syntaxhighlight lang="java">
<div class="TB">setString()</div>
boolean autoCommitDefault = conn.getAutoCommit();
</td>
try {
</tr>
conn.setAutoCommit(false);
 
/* You execute statements against conn here transactionally */
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
<td class="FormalW">
<div class="TB">VARCHAR2&nbsp;</div>
</td>
 
conn.commit();
<td class="FormalW">
} catch (Throwable e) {
<div class="TB">setString()</div>
try { conn.rollback(); } catch (Throwable e) { logger.warn("Could not rollback transaction", e); }
</td>
throw e;
</tr>
} finally {
try { conn.setAutoCommit(autoCommitDefault); } catch (Throwable e) { logger.warn("Could not restore AutoCommit setting",e); }
}
</syntaxhighlight>
 
For an example of a <code>CallableStatement</code> (to call stored procedures in the database), see the {{Javadoc:SE-guide|jdbc/getstart/callablestatement.html|JDBC API Guide}} documentation.
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
<td ROWSPAN="8" class="FormalW">
<div class="TB">NUMBER&nbsp;</div>
</td>
 
<syntaxhighlight lang="java">
<td class="FormalW">setBigDecimal()</td>
import java.sql.Connection;
</tr>
import java.sql.DriverManager;
import java.sql.Statement;
 
public class Mydb1 {
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
static String URL = "jdbc:mysql://localhost/mydb";
<td class="FormalW">
<div class="TB">setBoolean()&nbsp;</div>
</td>
</tr>
 
public static void main(String[] args) {
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
try {
<td class="FormalW">
Class.forName("com.mysql.jdbc.Driver");
<div class="TB">setByte()&nbsp;</div>
</td>
</tr>
 
Connection conn = DriverManager.getConnection(URL, "root", "root");
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
Statement stmt = conn.createStatement();
<td class="FormalW">
<div class="TB">setShort()&nbsp;</div>
String sql = "INSERT INTO emp1 VALUES ('pctb5361', 'kiril', 'john', 968666668)";
</td>
stmt.executeUpdate(sql);
</tr>
System.out.println("Inserted records into the table...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
</syntaxhighlight>
 
==JDBC drivers==
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
{{Main | JDBC driver}}
<td class="FormalW">
<div class="TB">setInt()&nbsp;</div>
</td>
</tr>
 
JDBC drivers are client-side [[Adapter pattern|adapters]] (installed on the client machine, not on the server) that convert requests from Java programs to a protocol that the DBMS can understand.
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
<td class="FormalW">
<div class="TB">setLong()&nbsp;</div>
</td>
</tr>
 
===Types===
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
Commercial and free drivers provide connectivity to most relational-database servers. These drivers fall into one of the following types:
<td class="FormalW">
<div class="TB">setFloat()&nbsp;</div>
</td>
</tr>
 
* [[JDBC driver#Type 1 Driver - JDBC-ODBC bridge|Type 1]] that calls native code of the locally available ODBC driver. (Note: In JDBC 4.2, JDBC-ODBC bridge has been removed<ref>{{cite web|url=https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/|title=Java JDBC API|website=docs.oracle.com|access-date=22 March 2018}}</ref>)
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
* [[JDBC driver#Type 2 Driver - Native-API Driver|Type 2]] that calls database vendor native library on a client side. This code then talks to database over the network.
<td class="FormalW">
* [[JDBC driver#Type 3 Driver - Network-Protocol Driver(MiddleWare Driver)|Type 3]], the pure-java driver that talks with the server-side middleware that then talks to the database.
<div class="TB">setDouble()</div>
* [[JDBC driver#Type 4 Driver - Database-Protocol Driver(Pure Java Driver)|Type 4]], the pure-java driver that uses database native protocol.
</td>
</tr>
 
Note also a type called an [[internal JDBC driver]] - a driver embedded with [[Java Runtime Environment|JRE]] in Java-enabled SQL databases. It is used for [[Java stored procedure]]s. This does not fit into the classification scheme above, although it would likely resemble either a type 2 or type 4 driver (depending on whether the database itself is implemented in Java or not). An example of this is the KPRB (Kernel Program Bundled) driver<ref>
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
{{cite book
<td class="FormalW">INTEGER</td>
| last1 = Greenwald
| first1 = Rick
| last2 = Stackowiak
| first2 = Robert
| last3 = Stern
| first3 = Jonathan
| year = 1999
| title = Oracle Essentials: Oracle Database 10g
| url = https://books.google.com/books?id=CTebAgAAQBAJ
| series = Essentials Series
| edition = 3
| ___location = Sebastopol, California
| publisher = O'Reilly Media, Inc.
| publication-date = 2004
| page = 318
| isbn = 9780596005856
| access-date = 2016-11-03
| quote = ''The in-database JDBC driver (JDBC KPRB)''[:] Java code uses the JDBC KPRB (Kernel Program Bundled) version to access SQL on the same server.
}}
</ref>
supplied with [[Oracle Database|Oracle RDBMS]]. "jdbc:default:connection" offers a relatively standard way of making such a connection (at least the Oracle database and [[Apache Derby]] support it). However, in the case of an internal JDBC driver, the JDBC client actually runs as part of the database being accessed, and so can access data directly rather than through network protocols.
 
===Sources===
<td class="FormalW">setInt()</td>
* [[Oracle Corporation|Oracle]] provides a [http://www.oracle.com/technetwork/java/index-136695.html list of some JDBC drivers and vendors]
</tr>
* [[Simba Technologies]] ships an SDK for building custom JDBC Drivers for any custom/proprietary relational data source
* CData Software ships type 4 JDBC Drivers for various applications, databases, and Web APIs.<ref>{{cite web|url=http://www.cdata.com/jdbc/|title=JDBC Drivers - CData Software|website=CData Software|access-date=22 March 2018}}</ref>
* RSSBus Type 4 JDBC Drivers for applications, databases, and web services<ref>{{cite web|url=http://www.rssbus.com/jdbc/|title=JDBC Drivers - CData Software|website=CData Software|access-date=22 March 2018|archive-date=22 December 2015|archive-url=https://web.archive.org/web/20151222115409/http://www.rssbus.com/jdbc/|url-status=dead}}</ref>
* DataDirect Technologies provides a comprehensive suite of fast Type 4 JDBC drivers for all major database they advertise as Type 5<ref name=datadirect>{{cite web
| url=http://www.datadirect.com/products/features/data-connectivity/type-5-jdbc/index.html
| title=New Type 5 JDBC Driver&nbsp;— DataDirect Connect
}}</ref>
* IDS Software provides a Type 3 JDBC driver for concurrent access to all major databases. Supported features include resultset caching, SSL encryption, custom data source, dbShield
* JDBaccess is a Java persistence library for [[MySQL]] and [[Oracle database|Oracle]] which defines major database access operations in an easy usable API above JDBC
* [[JNetDirect Incorporated|JNetDirect]] provides a suite of fully Sun J2EE certified high-performance JDBC drivers.
* JDBCR4 is a service program written by [[Scott Klement]] to allow access to JDBC from [[IBM RPG|RPG]] on the [[IBM i]].<ref>{{cite web|title=Access External Databases from RPG with JDBCR4 Meat of the Matter|url=http://iprodeveloper.com/rpg-programming/access-external-databases-rpg-jdbcr4|access-date=12 April 2016|date=28 June 2012}}</ref>
* [[HSQLDB]] is a [[Relational database management system|RDBMS]] with a JDBC driver and is available under a BSD license.
* SchemaCrawler<ref name=schemacrawler>{{cite web
| author=Sualeh Fatehi
| url=https://github.com/schemacrawler/SchemaCrawler
| title=SchemaCrawler
| work=GitHub
}}</ref> is an open source API that leverages JDBC, and makes database metadata available as plain old Java objects (POJOs)
 
==See also==
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
* [[GNU Data Access]] (GDA)
<td class="FormalW">FLOAT</td>
* [[JDBCFacade]]
* [[Open Database Connectivity]] (ODBC)
* [[Object–relational mapping]] (ORM)
 
== Citations ==
<td class="FormalW">setDouble()&nbsp;</td>
{{reflist}}
</tr>
 
== References ==
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
* {{cite book | last=Bai | first=Ying | title=SQL Server Database Programming with Java | publisher=[[Springer International Publishing]] | publication-place=Cham | year=2022 | isbn=978-3-030-92686-1 | doi=10.1007/978-3-031-06553-8}}
<td class="FormalW">CLOB</td>
* {{cite book | last=Horstmann | first=Cay | title=Core Java | publisher=Oracle Press Java | date=April 15, 2022 | isbn=978-0-13-787107-0}}
<td class="FormalW">setClob()&nbsp;</td>
</tr>
 
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
<td class="FormalW">BLOB</td>
<td class="FormalW">setBlob()&nbsp;</td>
</tr>
 
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
<td class="FormalW">
<div class="TB">RAW</div>
</td>
 
<td class="FormalW">
<div class="TB">setBytes()</div>
</td>
</tr>
 
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
<td class="FormalW">
<div class="TB">LONGRAW&nbsp;</div>
</td>
 
<td class="FormalW">
<div class="TB">setBytes()&nbsp;</div>
</td>
</tr>
 
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
<td ROWSPAN="3" class="FormalW">
<div class="TB">DATE&nbsp;</div>
</td>
 
<td class="FormalW">
<div class="TB">setDate()&nbsp;</div>
</td>
</tr>
 
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
<td class="FormalW">
<div class="TB">setTime()&nbsp;</div>
</td>
</tr>
 
<tr ALIGN=LEFT VALIGN=TOP class="FormalW">
<td class="FormalW">
<div class="TB">setTimestamp()&nbsp;</div>
</td>
</tr>
</table>
 
For an example of a <code>CallableStatement</code> (to call stored procedures in the database), see the {{Javadoc:SE-guide|jdbc/getstart/callablestatement.html|JDBC API Guide}}.
 
== Drivers ==
Drivers are client-side adaptors (they are installed in the client machine, not in the server) that convert requests from Java programs to a protocol that the DBMS can understand.
=== Types ===
 
There are commercial and free drivers available for most relational database servers. These drivers fall into one of the following types:
 
* [[JDBC type 1 driver|Type 1]], the JDBC-ODBC bridge
* [[JDBC type 2 driver|Type 2]], the Native-API driver
* [[JDBC type 3 driver|Type 3]], the network-protocol driver
* [[JDBC type 4 driver|Type 4]], the native-protocol drivers
* [[Internal JDBC driver]], driver embedded with JRE in Java-enabled SQL databases. Used for Java stored procedures.
* [[JDBC URL]], all Database Connection String
 
=== Sources ===
 
* [http://www.SQLSummit.com/JDBCVend.htm SQLSummit.com] publishes list of drivers, including JDBC drivers and vendors
* [[Sun Microsystems]] provides a [http://servlet.java.sun.com/products/jdbc/drivers list of some JDBC drivers and vendors]
* [http://www.simba.com/odbc-sdk.htm Simba Technologies] ships an SDK for building custom JDBC Drivers for any custom/proprietary relational data source
* [http://www.datadirect.com/products/jdbc/index.ssp DataDirect Technologies] provides a comprehensive suite of fast Type 4 JDBC drivers for all major database
* [http://www.inetsoftware.de/products/jdbc/ i-net software] provides fast Type 4 JDBC drivers for all major databases
* [http://uda.openlinksw.com/jdbc/ OpenLink Software] ships JDBC Drivers for a number of target databases, including Bridges to other data access mechanisms (e.g., ODBC, JDBC) which can provide more functionality than the targeted mechanism
 
== External links ==
 
==External links==
{{Commons category|JDBC}}
{{Wikibooks|Java Programming/Database Programming}}
* {{Javadoc:SE-guide|jdbc|JDBC API Guide}}
* {{Javadoc:SE|package=java.sql|java/sql|module=java.sql}} API [[Javadoc]] documentation
* {{Javadoc:SE|package=javax.sql|javax/sql|module=java.sql}} API Javadoc documentation
* [https://web.archive.org/web/20160111210342/http://orbroker.org/ O/R Broker] Scala JDBC framework
* [http://www.datadirect.com/knowledgebase/kbase.nsf/Code+Samples?OpenView&RestrictToCategory=Connect+for+JDBC DataDirect Technologies - JDBC Code Samples]
* [http://www.hsqldb.org/doc/2.0/util-guide/sqltool-chapt.html SqlTool] Open source, command-line, generic JDBC client utility. Works with any JDBC-supporting database.
* [http://java.sun.com/docs/books/tutorial/jdbc/ Sun tutorial]
* [http://codeoftheday.blogspot.com/2012/12/java-database-connectivity-jdbc-url.html JDBC URL Strings and related information of All Databases.]
* [http://java.sun.com/developer/technicalArticles//Database/dukesbakery/ Duke's Bakery - A JDBC Order Entry Prototype]
* [http://java.sun.com/developer/technicalArticles//Database/dbaccessor/ DBAccessor: A JDBC Wrapper Package]
* [http://java-source.net/open-source/database-engines List of Java Open Source Databases with JDBC drivers]
* [http://docs.maggi.cc/my_thesis_polijdbc.pdf A sample implementation of a tiny-JDBC layer for an embedded DBMS] (PDF) by Federico Maggi (Introduction in both Italian and English: Other chapters in English)
* [http://www.easysoft.com/developer/interfaces/jdbc/index.html JDBC Articles and Resources]
*[http://www.alnaja7.org/Programmer/393/JDBC/jdbc.htm Useful site for JDBC using Derby]
 
[[Category{{DEFAULTSORT:Java platform|Database Connectivity]]}}
[[Category:JavaJDK specification requests|Database Connectivitycomponents]]
[[Category:ApplicationJava programmingspecification interfacesrequests]]
[[Category:SQL data access]]
[[Category:DatabasesDatabase APIs]]
 
{{Databases}}
 
[[de:Java Database Connectivity]]
[[es:JDBC]]
[[fr:Java database connectivity]]
[[it:JDBC]]
[[nl:Java DataBase Connectivity]]
[[ja:JDBC]]
[[no:JDBC]]
[[pl:JDBC]]
[[pt:JDBC]]
[[ru:Java Database Connectivity]]
[[sv:JDBC]]
[[zh:JDBC]]