Java Database Connectivity
The Java Database Connectivity (JDBC) API is an interface for querying and
updating a database.
Connection
The Connection interface encapsulates the communication to a database.
A Connection is provided by either a DriverManager or a DataSource.
A DriverManager requires connection details such as the url and credentials,
but a DataSource hides the connection details behind an interface.
A DataSource is usually provided by an application
server through a lookup
service called the Java Naming and Directory Interface (JNDI). DataSources
are preferable to DriverManagers because they are more flexible and easier
to change.
Statements
Statements
are provided by a Connection to encapsulate SQL queries.
PreparedStatements
are pre-compiled
by the database and improve
performance for queries that are executed repeatedly or contain input
parameters. CallableStatements are used to execute stored procedures
that contain both input and output parameters.
ResultSets
ResultSets
are provided by Statements
to encapsulate the result
of a query. A ResultSet contains a cursor that can scroll through rows and
extract type-safe values. ResultSets can be configured to support
bidirectional scrolling as well as row modifications depending
on the capabilities
of the database.
SQL Injection
SQL injection is a popular attack vector that allows malicious queries to be
embedded into Statements that were
constructed out of string
concatenations. SQL injection can be prevented by using
PreparedStatements
to register input values.