Content deleted Content added
(96 intermediate revisions by 72 users not shown) | |||
Line 1:
{{Short description|API for Java}}
'''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.
|latest release date = {{Start date|
|latest preview version =
|latest preview date =
Line 13 ⟶ 14:
|website = {{Javadoc:SE-guide|jdbc|JDBC API Guide}}
}}
==History and implementation==
[[
{{cite web
| title = Sun Ships JDK 1.1 -- Javabeans Included
| date = 1997-02-19
| work = www.sun.com
| publisher = [[Sun Microsystems]]
|
| archive-url = https://web.archive.org/web/20080210044125/http://www.sun.com/smi/Press/sunflash/1997-02/sunflash.970219.0001.xml
|
| 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
}}
Line 32:
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>.
Starting with version 3.1, JDBC has been developed under the [[Java Community Process]].
JDBC 4.1, is specified by a maintenance release 1 of JSR 221<ref>
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>
{| class="wikitable"
|+ 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==
{| 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.
JDBC connections support creating and executing statements.
* {{Javadoc:SE|java/sql|Statement|module=java.sql}} – the
* {{Javadoc:SE|java/sql|PreparedStatement|module=java.sql}} – {{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}} – {{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
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.
There is an extension to the basic JDBC API in the {{Javadoc
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}}
==Examples==
When a Java application needs a database connection, one of the <code>DriverManager.getConnection()</code> methods is used to create a JDBC
<
Connection conn = DriverManager.getConnection(
"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
<
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
<
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate(
}
</syntaxhighlight>
Note that
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.
Line 99 ⟶ 179:
Data is retrieved from the database using a database query mechanism. The example below shows creating a statement and executing a query.
<
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(
) {
while (
int numColumns = rs.getMetaData().getColumnCount();
for (
// 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>
<
try (PreparedStatement ps =
conn.prepareStatement(
) {
// 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.
Line 134 ⟶ 214:
// positioned before the first row.
try (ResultSet rs = ps.executeQuery()) {
while (
int numColumns = rs.getMetaData().getColumnCount();
for (
// 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(
} // 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.
<
boolean autoCommitDefault = conn.getAutoCommit();
try {
Line 160 ⟶ 240:
conn.commit();
} catch (Throwable e) {
try { conn.rollback(); } catch (Throwable e) { logger.warn("Could not rollback transaction", e); }
throw e;
} 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.
<
import java.sql.Connection;
import java.sql.DriverManager;
Line 235 ⟶ 258:
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(URL, "root", "root");
Statement stmt = conn.createStatement();
String sql = "INSERT INTO emp1 VALUES ('pctb5361', '
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} catch (Exception e) {
}
}
}
</syntaxhighlight>
==JDBC drivers==
Line 260 ⟶ 283:
Commercial and free drivers provide connectivity to most relational-database servers. These drivers fall into one of the following types:
* [[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>)
* [[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.
* [[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.
* [[JDBC driver#Type 4 Driver - Database-Protocol Driver(Pure Java Driver)|Type 4]], the pure-java driver that uses database native protocol.
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>
{{cite book
| last1 = Greenwald
Line 273 ⟶ 296:
| last3 = Stern
| first3 = Jonathan
|
| title = Oracle Essentials: Oracle Database 10g
| url = https://books.google.com/books?id=CTebAgAAQBAJ
Line 287 ⟶ 310:
}}
</ref>
supplied with [[Oracle Database
===Sources===
* [[Oracle Corporation|Oracle]] provides a [http://www.oracle.com/technetwork/java/index-136695.html list of some JDBC drivers and vendors]
* [[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
Line 299 ⟶ 322:
}}</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|
* [[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=
}}</ref> is an open source API that leverages JDBC, and makes database metadata available as plain old Java objects (POJOs)
==See also==
* [[GNU Data Access]] (GDA)
* [[JDBCFacade]]
* [[Open Database Connectivity]] (ODBC)
* [[Object–relational mapping]] (ORM)
==
{{reflist}}
== References ==
* {{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}}
* {{cite book | last=Horstmann | first=Cay | title=Core Java | publisher=Oracle Press Java | date=April 15, 2022 | isbn=978-0-13-787107-0}}
==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
* [
* [http://www.hsqldb.org/doc/2.0/util-guide/sqltool-chapt.html SqlTool] Open source, command-line, generic JDBC client utility.
* [http://codeoftheday.blogspot.com/2012/12/java-database-connectivity-jdbc-url.html JDBC URL Strings and related information of All Databases.]
{{DEFAULTSORT:Database Connectivity}}
[[Category:
[[Category:Java specification requests]]
[[Category:SQL data access]]
[[Category:Database APIs]]
|