FACTOID # 158: The expatriate population from Cape Verde is larger than its domestic one.
 
 Home   Encyclopedia   Statistics   Countries A-Z   Flags   Maps   Education   Forum   FAQ   About 
 
WHAT'S NEW
RECENT ARTICLES
More Recent Articles »
 

Encyclopedia > Java Database Connectivity

JDBC is an 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 databases. An application programming interface (API) is a source code interface that a computer system or program library provides to support requests for services to be made of it by a Length. ... Java is a programming language originally developed by Sun Microsystems and released in 1995. ... This article does not cite any references or sources. ... A relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd. ...


The Java Platform, Standard Edition includes the JDBC API together with an ODBC implementation of the API enabling connections to any relational database that supports ODBC. This driver is native code and not Java, and is closed source.[1] Java Platform, Standard Edition or Java SE (formerly known up to version 5. ... In computing, Open Database Connectivity (ODBC) provides a standard software API method for using database management systems (DBMS). ... In computing, Open Database Connectivity (ODBC) provides a standard software API method for using database management systems (DBMS). ... A system of codes directly understandable by a computers CPU is termed this CPUs native or machine language. ... The text below is generated by a template, which has been proposed for deletion. ...

Contents

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 java.sql. Starting with version 3.0, JDBC has been developed under the Java Community Process. JSR 54 specifies JDBC 3.0 (included in J2SE 1.4), JSR 114 specifies the JDBC Rowset additions, and JSR 221 is the specification of JDBC 4.0 (included in Java SE 6). A Java package is a Java programming language mechanism for organizing classes into namespaces. ... The Java Community Process or JCP, established in 1995, is a formalized process which allows interested parties to be involved in the definition of future versions and features of the Java platform. ...


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 connections support creating and executing statements. These statements may be update statements such as SQL CREATE, 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: SQL (IPA: or IPA: ), commonly expanded as Structured Query Language, is a computer language designed for the retrieval and management of data in relational database management systems, database schema creation and modification, and database object access control management. ...

  • Statement – the statement is sent to the database server each and every time.
  • PreparedStatement – 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.
  • CallableStatement – used for executing stored procedures on the database.

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.


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.


There is an extension to the basic JDBC API in the javax.sql package that allows for scrollable result sets and cursor support among other things.


Example

The method Class.forName(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. (Some JVMs also require the class to be instantiated with .newInstance().)

 Class.forName( "com.somejdbcvendor.TheirJdbcDriver" ); 

In JDBC 4.0, it's no longer necessary to explicitly load JDBC drivers using Class.forName(). See JDBC 4.0 Enhancements in Java SE 6


When a Driver class is loaded, it creates an instance of itself and registers it with the DriverManager. This can be done by including the needed code in the driver class's static block. e.g. DriverManager.registerDriver(Driver driver)


Now when a connection is needed, one of the DriverManager.getConnection() methods is used to create a JDBC connection.

 Connection conn = DriverManager.getConnection( "jdbc:somejdbcvendor:other data needed by some jdbc vendor", "myLogin", "myPassword" ); 

The URL used is dependent upon the particular JDBC driver. It will always begin with the "jdbc:" protocol, but the rest is up to the particular vendor. Once a connection is established, a statement must be created.

 Statement stmt = conn.createStatement(); try { stmt.executeUpdate( "INSERT INTO MyTable( name ) VALUES ( 'my name' ) " ); } finally { //It's important to close the statement when you are done with it stmt.close(); } 

Note that connections, statements, and resultsets often tie up operating system resources such as sockets or file descriptors. In the case of connections to remote database servers, further resources are tied up on the server, eg. cursors for currently open resultsets. It is vital to close() any JDBC object as soon as it has played its part; garbage collection should not be relied upon. Forgetting to close() things properly results in spurious errors and misbehaviour. The above try-finally construct is a recommended code pattern to use with JDBC objects. It has been suggested that Maintenance OS be merged into this article or section. ...


Data is retrieved from the database using a database query mechanism. The example below shows creating a statement and executing a query.

 Statement stmt = conn.createStatement(); try { ResultSet rs = stmt.executeQuery( "SELECT * FROM MyTable" ); 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) ); } } } finally { rs.close(); } } finally { stmt.close(); } 

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.


An example of a PreparedStatement query. Using conn and class from first example.

 PreparedStatement 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 first occurrence of the ?, // the second parameter tells Java to replace it with // the second item. // The nth parameter corresponds to the nth ? ps.setString(1, "Poor Yorick"); ps.setInt(2, 8008); // The ResultSet rs, receives the SQL Query response. ResultSet 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 } finally { rs.close(); } } finally { ps.close; } // try 

When a database operation fails, an SQLException is raised. 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 SQLException be translated into an application domain exception (an unchecked one) that eventually results in a transaction rollback and a notification to the user.


Here are examples of host database types, Java can convert to with a function.

setXXX() Methods
Oracle Datatype setXXX()
CHAR setString()
VARCHAR2 setString()
NUMBER setBigDecimal()
setBoolean()
setByte()
setShort()
setInt()
setLong()
setFloat()
setDouble()
INTEGER setInt()
FLOAT setDouble()
CLOB setClob()
BLOB setBlob()
RAW setBytes()
LONGRAW setBytes()
DATE setDate()
setTime()
setTimestamp()

For an example of a CallableStatement (to call stored procedures in the database), see the JDBC API Guide.


JDBC Drivers

JDBC Drivers are client-side adaptors (they are installed on the client machine, not on 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:

  • Type 1, the JDBC-ODBC bridge
  • Type 2, the Native-API driver
  • Type 3, the network-protocol 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

Schematic of the JDBC-ODBC bridge The JDBC type 1 driver, also known as the JDBC-ODBC bridge is a database driver implementation that employs the ODBC driver to connect to the database. ... Schematic of the Native API driver The JDBC type 2 driver, also known as the Native-API driver is a database driver implementation that uses the client-side libraries of the database. ... Schematic of the Network Protocol driver The JDBC type 3 driver, also known as the network-protocol driver is a database driver implementation which makes use of a middle-tier between the calling program and the database. ... Schematic of the Native-Protocol driver The JDBC type 4 driver, also known as the native-protocol driver is a database driver implementation that converts JDBC calls directly into the vendor-specific database protocol. ...

Sources

  • SQLSummit.com publishes list of drivers, including JDBC drivers and vendors
  • Sun Microsystems provides a list of some JDBC drivers and vendors
  • Simba Technologies ships an SDK for building custom JDBC Drivers for any custom/proprietary relational data source
  • DataDirect Technologies provides a comprehensive suite of fast Type 4 JDBC drivers for all major database
  • 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.
  • i-net software provides fast Type 4 JDBC drivers for all major databases
  • 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
  • JDBaccess is a Java persistence library for MySQL and Oracle which defines major database access operations in an easy usable API above JDBC

Sun Microsystems, Inc. ... Simba Technologies is a supplier of standards-based data access solutions located in Vancouver, British Columbia, Canada. ... MySQL (pronounced ) is a multithreaded, multi-user SQL database management system (DBMS)[1] which has, according to MySQL AB, more than 10 million installations. ... The term Oracle database refers to both the database management system (DBMS) software released by Oracle Corporation as Oracle RDBMS, and to individual databases which are managed by such software. ...

External links

Topics in database management systems (DBMS)view  talk  edit )

Concepts
Database • Database models • Database storage • Relational model • Distributed DBMS • ACID • Null
Relational database • Relational algebra • Relational calculus • Database normalization • Referential integrity • Relational DBMS 
Primary key, Foreign key, Surrogate key, Superkey, Candidate key  Javadoc is a computer software tool from Sun Microsystems for generating API documentation into HTML format from Java source code. ... Scriptella is an open source ETL (Extract-Transform-Load) and script execution tool. ... Extract, transform, and load (ETL) is a process in data warehousing that involves extracting data from outside sources, transforming it to fit business needs, and ultimately loading it into the data warehouse. ... A database management system (DBMS) is computer software designed for the purpose of managing databases. ... This article does not cite any references or sources. ... A data model is not just a way of structuring data: it also defines a set of operations that can be performed on the data. ... Database tables/indexes are typically stored in memory or on hard disk in one of many forms, ordered/unordered Flat files, ISAM, Heaps, Hash buckets or B+ Trees. ... The relational model for database management is a database model based on predicate logic and set theory. ... According to Elmasri and Navathe (2004, p. ... Acidity redirects here. ... The Greek lowercase omega (ω) character is historically used by academics to represent Null in relational databases. ... A relational database is a database that conforms to the relational model, and refers to a databases data and schema (the databases structure of how that data is arranged). ... Relational algebra, an offshoot of first-order logic, is a set of relations closed under operators. ... The relational calculus refers to the two calculi, the tuple calculus and the domain calculus, that are part of the relational model for databases and that provide a declarative way to specify database queries. ... Database normalization is a design technique for structuring relational database tables. ... An example of a database that has not enforced referential integrity. ... A relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd. ... In database design, a primary key is a value that can be used to identify a unique row in a table. ... In the context of relational databases, a foreign key is a referential constraint between two tables[1]. The foreign key identifies a column or a set of columns in one (referencing) table that refers to a column or set of columns in another (referenced) table. ... A surrogate key is a unique primary key generated by the relational database management system that is not derived from any data in the database and whose only significance is to act as the primary key. ... A superkey is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. ... In the relational model a candidate key of a relation variable (relvar) is a set of attributes of that relvar such that (1) at all times it holds in the relation assigned to that variable that there are no two distinct tuples with the same values for these attributes and...

Objects
Trigger • View • Table • Cursor • Log • Transaction • Index 
Stored procedure • Partition A database trigger is procedural code that is automatically executed in response to certain events on a particular table in a database. ... In database theory, a view is a virtual or logical table composed of the result set of a query. ... In relational databases, SQL databases, and flat file databases, a table is a set of data elements (values) that is organized using a model of horizontal rows and vertical columns. ... In database packages, the term cursor refers to a control structure for the successive traversal (and potential processing) of records in a result set as returned by a query. ... In in the field of databases in computer science, a transaction log (also database log or binary log) is a history of actions executed by a database management system to guarantee ACID properties over crashes or hardware failures. ... A database transaction is a unit of interaction with a database management system or similar system that is treated in a coherent and reliable way independent of other transactions that must be either entirely completed or aborted. ... It has been suggested that Bitmap index be merged into this article or section. ... A stored procedure is a subroutine available to applications accessing a relational database system. ... A partition is a division of a logical database or its constituting elements into distinct independent parts. ...

Topics in SQL
Select • Insert • Update • Merge • Delete • Join • Union • Create • Drop
  Begin work • Commit • Rollback • Truncate • Alter SQL (IPA: or IPA: ), commonly expanded as Structured Query Language, is a computer language designed for the retrieval and management of data in relational database management systems, database schema creation and modification, and database object access control management. ... A SELECT statement in SQL returns a result set of records from one or more tables. ... An SQL INSERT statement adds one or more records to a table in a relational database. ... An UPDATE statement in SQL changes data in one or more records in a relational database management system. ... Wikipedia does not have an article with this exact name. ... It has been suggested that this article or section be merged into Data Manipulation Language. ... A JOIN clause in SQL combines records from two tables in a relational database and results in a new (temporary) table, also called joined table. ... In SQL the UNION operator combines the results of two SQL queries into a single table of all matching rows. ... A CREATE statement in SQL creates an object inside of a relational database management system (RDBMS). ... A DROP statement in SQL removes an object from a relational database management system (RDBMS). ... It has been suggested that this article or section be merged into Database transaction. ... A COMMIT statement in SQL ends a transaction within a relational database management system (RDBMS) and makes all changes visible to other users. ... In database technologies, a rollback is an operation which returns the database to some previous state. ... The Truncate statement removes all the data from a table. ... An ALTER statement in SQL changes the properties of an object inside of a relational database management system (RDBMS). ...

Implementations of database management systems

Types of implementations
Relational • Flat file • Deductive • Dimensional • Hierarchical • Object oriented • Object relational • Temporal • XML data stores A relational database is a database that conforms to the relational model, and refers to a databases data and schema (the databases structure of how that data is arranged). ... A simple diagram depicting conversion of a CSV-format flat file database table into a relational database table. ... A deductive database system is a database system which can make deductions (ie: infer additional rules or facts) based on rules and facts stored in the (deductive) database. ... A dimensional database is one which, rather than storing data in multiple two dimensional tables (as a relational databases does), represents key data entities as different dimensions. ... In a hierarchical data model, data are organized into a tree-like structure. ... In an object oriented database, information is represented in the form of objects like in object oriented programming. ... An object-relational database (ORD) or object-relational database management system (ORDBMS) is a relational database management system that allows developers to integrate the database with their own custom data types and methods. ... A temporal database is a database management system with built-in time aspects, e. ... In Software engineering, an XML database is a data persistence software system that allows data to be imported, accessed and exported in the XML format. ...

Database products
Object-oriented (comparison) • Relational (comparison) The following is a list of object-oriented database management systems. ... This article or section is not written in the formal tone expected of an encyclopedia article. ... // 4th Dimension Greenplum CA-Datacom Dataphor Daffodil database EnterpriseDB eXtremeDB DB2 FileMaker Greenplum Helix database Informix InterBase Kognitio, WX2 Linter Matisse Microsoft Jet Database Engine (part of Microsoft Access) Microsoft SQL Server Microsoft Visual FoxPro Mimer SQL mSQL Netezza NonStop SQL Openbase Oracle Oracle Rdb for OpenVMS OpenLink Virtuoso Universal... The following tables compare general and technical information for a number of relational database management systems. ...

Components
Query language • Query optimizer • Query plan • ODBC • JDBC Query languages are computer languages used to make queries into databases and information systems. ... The query optimizer is a component of database management system that is used to analyzes queries submitted to database server for execution, and then determines the optimal way to execute the query. ... A query plan (or query execution plan) is an set of steps used to access information in a SQL relational database management system. ... In computing, Open Database Connectivity (ODBC) provides a standard software API method for using database management systems (DBMS). ...


  Results from FactBites:
 
JDBC - Java Database Connectivity (1525 words)
JDBC is commonly used to connect a user program to a "behind the scenes" database, regardless of what database management software is used to control the database.
Databases are composed of tables, which in turn are composed of rows.
In this case, we are going to query a database table for all its records, and display the result set to the command line.
  More results at FactBites »

 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your location
Your comments
Please enter the 5-letter protection code


Lesson Plans | Student Area | Student FAQ | Reviews | Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms.