database
database
- Connect to a database
-
JDBC Benefits
3. It's very simple and small that is used to provide a means of managing the
different types of JDBC database driver running on an application.
4. The main responsibility of JDBC database driver is to load all the drivers
found in the system properly as well as to select the most appropriate
driver from opening a connection to a database. The Driver Manager also
helps to select the most appropriate driver from the previously loaded
drivers when a new open database is connected.
JDBC Test Suite
• The JDBC driver test suite helps you to determine that
JDBC drivers will run your program.
• It ensures that the driver behaves correctly and
supports the required features and functionality of
the JDBC API.
• The JDBC Test Suite is essential for developers and
database vendors to validate the compatibility and
reliability of their JDBC drivers.
• It is used to test the operation(such as insertion,
deletion, updation) being performed by JDBC Drivers.
JDBC-ODBC Bridge
• The Java Software bridge provides JDBC access
via ODBC drivers.
• Note that you need to load ODBC binary code
onto each client machine that uses this driver.
• This driver translates JDBC method calls into
ODBC function calls.
• The Bridge implements Jdbc for any database for
which an Odbc driver is available.
• The Bridge is always implemented as the
sun.jdbc.odbc Java package and it contains a
native library used to access ODBC.
Basic steps to use a database in Java
1.Establish a connection (
Register Driver class and
create connection)
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections
Understanding basic JDBC steps
• Obtaining connection
• Creating JDBC statement
• Executing SQL statement
• Closing connection
• In JDBC (Java Database Connectivity), the
DriverManager class is a crucial part of the
API.
• It manages a
– list of database drivers
– handles establishing a connection to a database
by selecting an appropriate driver from the list of
registered drivers.
Obtaining connection
A. DriverManager.registerDriver(Driverinstance)
ex:
DriverManager.registerDriver(new
sun.jdbc.odbc.JdbcOdbcDriver());
B. Class.forName(Driver_class_name);
Class.forName(sun.jdbc.odbc.JbcOdbcDriver);
C. System.setProperty(“jdbc.driver”,”
sun.jdbc.odbc.JbcOdbcDriver”);
OR
Java -Djava.drivers=sun.jdbc.odbc.JbcOdbcDriver
myProg
Establish a connection
1. Load driver
import java.sql.*;
1. Load the vendor specific driver
• Load the JDBC Driver: driver must be in the CLASSPATH environment
variable and/or within the application server/containers relevant libraries.
A class is loaded into the JVM for use later, when we want to open a
connection.
ClassNotFoundException
• Class.forName("com.mysql.jdbc.Drive");
When the driver is loaded into memory, it registers itself with the
java.sql.DriverManager classes as an available database driver.
MySQL
● Driver Class: com.mysql.cj.jdbc.Driver
● JAR File: mysql-connector-java-x.x.x.jar
PostgreSQL
● Driver Class: org.postgresql.Driver
● JAR File: postgresql-x.x.x.jar
Oracle
● Driver Class: oracle.jdbc.driver.OracleDriver
● JAR File: ojdbc8.jar (for Java 8 and higher)
IBM DB2
● Driver Class: com.ibm.db2.jcc.DB2Driver
● JAR File: db2jcc4.jar
SQLite
MariaDB
H2 Database
Apache Derby
Informix
Teradata
– Connection con =
DriverManager.getConnection(
"jdbc:mysql://10.10.13.202:3306/test", username,
passwd);
3. Create JDBC Statements
Statement
Prepared Statement
Callable Statement
Statement
• Use for general-purpose access to your database.
• Useful when you are using static SQL statements at
runtime.
• The Statement interface cannot accept parameters.
• Statement is simple SQL statement and takes no
parameters, execute and compile every time when
request is generated to database server.
• You obtain a JDBC Statement from a JDBC Connection.
Once you have a Java Statement instance you can
execute either a database query or an database
update with it
Creating Statement Object:
while(result.next()) {
}
Execute an Update via a Statement
Statement statement = connection.createStatement();
1. prepareStatement(String sql):
1. prepareCall(String sql):
CallableStatement cstmt = conn.prepareCall("{call myStoredProc(?, ?)}");
● Creates a CallableStatement object for calling stored procedures.
Prepared Statement
• derived from Statement
• If you want to execute a Statement object many times, it usually
reduces execution time.
• PreparedStatement is precompiled SQL statement and reside in
PreparedStatement object.
• This PreparedStatement object executes multiple times SQL
statement without compiling it again and again.
• This is kind of caching SQL statement and execute on parameters
specification. First time when it executes, it runs slow but after
that it runs much faster than simple Statement Object.
• Sometimes it is called dynamic statement because it takes
parameter setter option.
• A SQL statement is given inside when PreparedStatement is
creating.
• PreparedStatement is in java.sql.PreparedStatement
How to get the instance of
PreparedStatement?
The prepareStatement() method of Connection interface is used to
return the object of PreparedStatement. Syntax:
4. int i=stmt.executeUpdate();
2. stmt.setInt(1,101);
3. int i=stmt.executeUpdate();
2. ResultSet rs=stmt.executeQuery();
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }
Example of PreparedStatement to
insert records until user press n
import java.sql.*;
import java.io.*;
class RS{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localho
st:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("insert into
emp130 values(?,?,?)");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
do{
System.out.println("enter id:"); int id=Integer.parseInt(br.readLine());
System.out.println("enter name:"); String name=br.readLine();
System.out.println("enter salary:"); float salary=Float.parseFloat(br.readLine());
ps.setInt(1,id);
ps.setString(2,name);
ps.setFloat(3,salary);
int i=ps.executeUpdate();
System.out.println(i+" records affected");
• next() method is actually called before the first record is accessed. That means,
that the ResultSet starts out pointing before the first record.
• Once next() has been called once, it points at the first record.
Accessing Column Values
When iterating the ResultSet you want to access the column values of each record. You
do so by calling one or more of the many getXXX() methods. You pass the name of the
column to get the value of, to the many getXXX() methods. For instance:
while(result.next()) {
result.getString ("name");
result.getInt ("age");
result.getBigDecimal("coefficient");
// etc.
}
There are a lot of getXXX() methods you can call, which return the value of the column
as a certain data type, e.g. String, int, long, double, BigDecimal etc. They all take the
name of the column to obtain the column value for, as parameter.
result.getArray("columnName"); result.getInt("columnName");
result.getAsciiStream("columnName"); result.getLong("columnName");
result.getBigDecimal("columnName"); result.getNCharacterStream("columnNa
result.getBinaryStream("columnName"); me");
result.getBlob("columnName"); result.getObject("columnName");
result.getBoolean("columnName"); result.getRef("columnName");
result.getBlob("columnName"); result.getRowId("columnName");
result.getShort("columnName");
result.getBoolean("columnName");
result.getSQLXML("columnName");
result.getByte("columnName");
result.getString("columnName");
result.getBytes("columnName");
result.getTime("columnName");
result.getCharacterStream("columnNam
result.getTimestamp("columnName");
e");
result.getUnicodeStream("columnName")
result.getClob("columnName");
;
result.getDate("columnName"); result.getURL("columnName");
result.getDouble("columnName");
result.getFloat("columnName");
The getXXX() methods also come in versions that take a column index instead of a
column name. For instance:
while(result.next()) {
result.getString (1);
result.getInt (2);
result.getBigDecimal(3);
// etc.
}
The index of a column typically depends on the index of the column in the SQL
statement. For instance, the SQL statement
select name, age, coefficient from person
has three columns. The column name is listed first, and will thus have index 1 in the
ResultSet. The column age will have index 2, and the column coefficient will have index
3.
Sometimes you do not know the index of a certain column ahead of time. For
instance, if you use a select * from type of SQL query, you do not know the
sequence of the columns.
If you do not know the index of a certain column you can find the index of that
column using the ResultSet.findColumn(String columnName) method, like
this:
int nameIndex = result.findColumn("name");
int ageIndex = result.findColumn("age");
int coeffIndex = result.findColumn("coefficient");
while(result.next()) {
String name = result.getString (nameIndex);
int age = result.getInt (ageIndex);
BigDecimal coefficient = result.getBigDecimal (coeffIndex);
}
ResultSet Type, Concurrency and
Holdability
When you create a ResultSet there are three attributes you can set. These are:
1. Type
2. Concurrency
3. Holdability
You set these already when you create the Statement or PreparedStatement
Statement statement = connection.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_OVER_COMMIT
);
PreparedStatement statement =
connection.prepareStatement(sql,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_OVER_COMMIT
);
What are different types of resultset
in JDBC?
• Forward-only
As name suggest, this type can only move forward and
are non-scrollable.
• Scroll-insensitive
This type is scrollable which means the cursor can
move in any direction. It is insensitive which means
any change to the database will not show change in
the resultset while it open.
• Scroll-sensitive
This type allows cursor to move in any direction and
also propagates the changes done to the database
Scrollable Result Sets
• In JDBC1.0, result sets could be navigated in
only one direction (forward) and starting at
only one point (first row)
• Since JDBC 2.0, the cursor can be
manipulated as if it were a array index
• Methods exist for reading both forward and
backward, for starting from any row, and
for testing the current cursor location.
Creating Scrollable Result Sets
• Statement object created with parameters to indicate
specific capabilities
• Connection.createStatement() method can have up to
three parameters:
– resultSetType – type of scrolling to be used
– resultSetConcurrency – indicates whether the result set can be
updated
– resultSetHoldability – specifies whether to close cursors when a
commit is done
• Example
– stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Constants in Result Sets
• Cursor Related Constants
– TYPE_FORWARD_ONLY
• JDBC 1.0-style navigation in which the cursor starts
at the first row and can only move forward.
– TYPE_SCROLL_INSENSITIVE
• All cursor positioning methods are enabled; the
result set doesn’t reflect changes made by others in
the underlying table.
– TYPE_SCROLL_SENSITIVE
• All cursor positioning methods are enabled the
result set reflects changes made by others in the
underlying table.
Constants in Result Sets (contd.)
• Updating Record Sets
– CONCUR_READ_ONLY
• The results set won’t be updatable
– CONCUR_UPDATABLE
• Rows can be added and deleted, and columns can
be updated.
• Closing Cursors
– HOLD_CURSORS_OVER_COMMIT
• Do not close cursors after a commit is done.
– CLOSE_COURSORS_AT_COMMIT
• Close cursors when a commit is done.
callable statement
A stored procedure is a group of SQL statements
that form a logical unit and perform a particular
task, and they are used to encapsulate a set of
operations or queries to execute on a database
server
Stored procedures can be compiled and
executed with different parameters and results,
and they can have any combination of input,
output, and input/output parameters.
Create a Procedure in Database
The procedure is created in the database using
the CREATE PROCEDURE statement
For the sake of demonstration, we will create a new stored
procedure named get_candidate_skill that accepts
candidate_id as the IN parameter and returns a result set that
contains the skills of the candidate
DELIMITER $$
CREATE PROCEDURE get_candidate_skill(IN candidate_id INT)
BEGIN
SELECT candidates.id, first_name,last_name,
skills.name AS skill
FROM candidates
INNER JOIN candidate_skills ON candidates.id =
candidate_skills.candidate_id
INNER JOIN skills ON skills.id = candidate_skills.skill_id
WHERE candidates.id = candidate_id;
END$$
DELIMITER ;
Let’s call this stored procedure for candidate id
with value 122.
CALL get_candidate_skill(122);
To call stored procedures or stored functions in MySQL
from JDBC, you use CallableStatement object, which
inherits from PreparedStatement object.
The general syntax of calling a stored procedure is as
follows:
{?= call procedure_name(param1,param2,...)}
• You wrap the stored procedure call within braces ({}).
• If the stored procedure returns a value, you need to
add the question mark and equal (?=) before the call
keyword.
• If a stored procedure does not return any values, you
just omit the ?= sign.
• In case the stored procedure accepts any parameters,
you list them within the opening and closing
parentheses after the stored procedure’s name.
The following are examples of using the syntax for
calling stored procedures in different contexts:
IN parameters
IN is the default mode.
When you define an IN parameter in a stored procedure,
the calling program has to pass an argument to the stored
procedure. In addition, the value of an IN parameter is
protected.
It means that even the value of the IN parameter is
changed inside the stored procedure, its original value is
retained after the stored procedure ends. In other words,
the stored procedure only works on the copy of the IN
parameter.
OUT parameters
The value of an OUT parameter can be changed
inside the stored procedure and its new value is
passed back to the calling program. Notice that the
stored procedure cannot access the initial value of
the OUT parameter when it starts.
INOUT parameters
An INOUT parameter is a combination of IN and OUT
parameters. It means that the calling program may
pass the argument, and the stored procedure can
modify the INOUT parameter, and pass the new value
back to the calling program.
Defining a parameter
Here is the basic syntax of defining a parameter
in stored procedures:
DELIMITER ;
CALL GetOfficeByCountry('USA');
CALL GetOfficeByCountry('France')
DELIMITER $$
DELIMITER ;
To find the number of orders that already shipped, you
call GetOrderCountByStatus and pass the order status as
of Shipped, and also pass a session variable ( @total ) to
receive the return value.
CALL GetOrderCountByStatus('Shipped',@total);
SELECT @total;
To get the number of orders that are in-process, you call
the stored procedure GetOrderCountByStatus as follows:
DELIMITER ;
SET @counter = 1;
CALL SetCounter(@counter,1); -- 2
CALL SetCounter(@counter,1); -- 3
CALL SetCounter(@counter,5); -- 8
SELECT @counter; -- 8
CREATE PROCEDURE `summary_report`(
IN title VARCHAR(45),OUT totalBooks INT,
OUT totalValue DOUBLE, INOUT highPrice DOUBLE
)
BEGIN
DECLARE maxPrice DOUBLE;
SELECT COUNT(*) AS bookCount, SUM(price) as total
FROM book b JOIN author a ON b.author_id = a.author_id
AND b.title LIKE CONCAT('%', title, '%')
INTO totalBooks, totalValue;
SELECT MAX(price) FROM book WHERE price INTO
maxPrice;
IF (maxPrice > highPrice) THEN
SET highPrice = maxPrice;
END IF;
END
To retrieve the values of the OUT and INOUT
parameters, JDBC requires these parameters
must be registered before calling the procedure,
by invoking the following method on
CallableStatementobject:
void registerOutParameter(int parameterIndex,
int sqlType)
CallableStatement statement = conn.prepareCall("{call
summary_report(?, ?, ?, ?)}");
statement.registerOutParameter(2, Types.INTEGER);
statement.registerOutParameter(3, Types.DOUBLE);
statement.registerOutParameter(4, Types.DOUBLE);
statement.setString(1, "Java");
statement.setDouble(4, 50);
statement.execute();
Integer totalBook = (Integer) statement.getObject(2,
Integer.class);
Double totalValue = statement.getDouble(3);
Double highPrice = statement.getDouble("highPrice");
public class StoredProcedureCallExample2 {
public static void main(String[] args) {
String dbURL = "jdbc:mysql://localhost:3306/booksdb";
String user = "root";
String password = "P@ssw0rd";
try {
Connection conn =
DriverManager.getConnection(dbURL, user, password);
CallableStatement statement = conn.prepareCall("{call
summary_report(?, ?, ?, ?)}");
statement.registerOutParameter(2, Types.INTEGER);
statement.registerOutParameter(3, Types.DOUBLE);
statement.registerOutParameter(4, Types.DOUBLE);
statement.setString(1, "Java");
statement.setDouble(4, 50);
statement.execute();
Integer totalBook = (Integer) statement.getObject(2, Integer.class);
Double totalValue = statement.getDouble(3);
Double highPrice = statement.getDouble("highPrice");
statement.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
Calling a Stored Procedure
Returning a Result Set from Java
CREATE PROCEDURE `get_books`(IN rate INT)
BEGIN
SELECT * FROM book WHERE rating >= rate;
END
CallableStatement statement = conn.prepareCall("{call
get_books(?)}");
statement.setInt(1, 5);
boolean hadResults = statement.execute();
while (hadResults) {
ResultSet resultSet = statement.getResultSet();
// process result set
while (resultSet.next()) {
// retrieve values of fields
String title = resultSet.getString("title");
}
hadResults = statement.getMoreResults();
}
Transaction Management in JDBC
If your JDBC Connection is in auto-commit mode, which it is by default, then every
SQL statement is committed to the database upon its completion.
That may be fine for simple applications, but there are three reasons why you may
want to turn off the auto-commit and manage your own transactions −
To increase performance.
Transactions enable you to control if, and when, changes are applied to the
database. It treats a single SQL statement or a group of SQL statements as one
logical unit, and if any statement fails, the whole transaction fails.
Transaction Management in JDBC
To enable manual- transaction support instead of the auto-commit mode that the
JDBC driver uses by default, use the Connection object's setAutoCommit() method. If
you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass
a boolean true to turn it back on again.
For example, if you have a Connection object named conn, code the following to turn
off auto-commit −\
conn.setAutoCommit(false);
Commit & Rollback
Once you are done with your changes and you want to commit the changes then call
commit() method on connection object as follows −
conn.commit( );
Otherwise, to roll back updates to the database made using the Connection named
conn, use the following code −
conn.rollback( );
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
con.commit();
con.close();
}}
import java.sql.*;
import java.io.*;
class TM{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:15
21:xe","system","oracle");
con.setAutoCommit(false);
System.out.println("enter id");
String s1=br.readLine();
int id=Integer.parseInt(s1);
System.out.println("enter name");
String name=br.readLine();
System.out.println("enter salary");
String s3=br.readLine();
int salary=Integer.parseInt(s3);
ps.setInt(1,id);
ps.setString(2,name);
ps.setInt(3,salary);
ps.executeUpdate();
System.out.println("commit/rollback");
String answer=br.readLine();
if(answer.equals("commit")){
con.commit();
}
if(answer.equals("rollback")){
con.rollback();
}
System.out.println("Want to add more records y/n");
String ans=br.readLine();
if(ans.equals("n")){
break;
} }
con.commit();
System.out.println("record successfully saved");
con.close();//before closing connection commit() is called
}catch(Exception e){System.out.println(e);}
JDBC - Batch Processing
Batch Processing allows you to group related SQL statements into a batch
and submit them with one call to the database.
When you send several SQL statements to the database at once, you
reduce the amount of communication overhead, thereby improving
performance.
JDBC drivers are not required to support this feature. You should use the
DatabaseMetaData.supportsBatchUpdates() method to determine if the
target database supports batch update processing. The method returns
true if your JDBC driver supports this feature.
Just as you can add statements to a batch for processing, you can
remove them with the clearBatch() method. This method removes all
the statements you added with the addBatch() method. However, you
cannot selectively choose which statement to remove.
Batching with Statement Object
Here is a typical sequence of steps to use Batch Processing with Statement
Object −
• Add as many as SQL statements you like into batch using addBatch()
method on created statement object.
Add as many as SQL statements you like into batch using addBatch() method on
created statement object.
use empdb;
DatabaseMetaData databaseMetaData =
connection.getMetaData();
Once you have obtained this DatabaseMetaData
instance, you can call methods on it to obtain
the meta data about the database.
Database Product Name and
Version
You can obtain the database product name and
version, like this:
int majorVersion =
databaseMetaData.getDatabaseMajorVersion();
int minorVersion =
databaseMetaData.getDatabaseMinorVersion();
String productName =
databaseMetaData.getDatabaseProductName();
String productVersion =
databaseMetaData.getDatabaseProductVersion();
Database Driver Version
You can obtain the driver version of the JDBC
driver used, like this:
int driverMajorVersion =
databaseMetaData.getDriverMajorVersion();
int driverMinorVersion =
databaseMetaData.getDriverMinorVersion();
Listing Tables
You can obtain a list of the defined tables in your database,
via the DatabaseMetaData. Here is how that is done:
String catalog = null;
String schemaPattern = null;
String tableNamePattern = null;
String[] types = null;
ResultSet result = databaseMetaData.getTables(
catalog, schemaPattern, tableNamePattern, types );
while(result.next()) {
String tableName = result.getString(3);
}
Listing Columns in a Table
String catalog = null;
String schemaPattern = null;
String tableNamePattern = "my_table";
String columnNamePattern = null;
while(result.next()){
String columnName = result.getString(4);
int columnType = result.getInt(5);
}
Primary Key for Table
It is also possible to obtain the primary key of a table. You do so,
like this:
while(result.next()){
String columnName = result.getString(4);
}
JDBC Architecture
• The Bridge driver uses the odbc subprotocol. URLs for this
subprotocol are of the form:
• jdbc:odbc:<data-source-name>[;<attribute-
name>=<attribute-value>]*
• For example:
jdbc:odbc:sybase
jdbc:odbc:mydb;UID=me;PWD=secret
jdbc:odbc:ora123;Cachesize=300
Function
• Translates query obtained by JDBC into
corresponding ODBC query, which is then
handled by the ODBC driver.
• Sun provides a JDBC-ODBC Bridge driver.
sun.jdbc.odbc.JdbcOdbcDriver. This driver is
native code and not Java, and is closed source.
• Client -> JDBC Driver -> ODBC Driver ->
Database
Type 2 Java to Native API.
Type 2 Java to Native API.
• Type 2 drivers use the Java Native Interface (JNI) to
make calls to a local database library API.
• This driver converts the JDBC calls into a database
specific call for databases such as SQL, ORACLE etc.
• This driver communicates directly with the database
server.
• It requires some native code to connect to the
database.
• Type 2 drivers are usually faster than Type 1 drivers.
Like Type 1 drivers, Type 2 drivers require native
database client libraries to be installed and configured
on the client machine.
Type 3 Java to Network Protocol Or All-
Java Driver.
• Type 3 drivers are pure Java drivers that use a
proprietary network protocol to communicate
with JDBC middleware on the server.
• The middleware then translates the network
protocol to database-specific function calls.
• Type 3 drivers are the most flexible JDBC
solution because they do not require native
database libraries on the client and can
connect to many different databases on the
back end.
• Type 3 drivers can be deployed over the
Internet without client installation.
Java-------> JDBC statements------> SQL
statements ------> databases.
Type 4 Java to Database Protocol.
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Or any other
driver
}
catch(Exception x){
System.out.println( "Unable to load the driver class!" );
}
• One drawback to Type 4 drivers is that they are
database specific. Unlike Type 3 drivers, if your back-
end database changes, you may save to purchase and
deploy a new Type 4 driver (some Type 4 drivers are
available free of charge from the database
manufacturer).
• However, because Type drivers communicate directly
with the database engine rather than through
middleware or a native library, they are usually the
fastest JDBC drivers available.
• This driver directly converts the java statements to SQL
statements.
• JDBC Basics - Java Database Connectivity Steps
• Before you can create a java jdbc connection to
the database, you must first import the java.sql
package.
• import java.sql.*;
• The star ( * ) indicates that all of the classes in
the package java.sql are to be imported.
• Steps:
1. Loading Driver
2. Establishing Connection
3. Executing Statements
4. Getting Results
5. Closing Database Connection
2. Creating a oracle jdbc Connection
• The JDBC DriverManager class defines objects which can connect
Java applications to a JDBC driver.
• DriverManager is considered the backbone of JDBC architecture.
• DriverManager class manages the JDBC drivers that are installed
on the system. Its getConnection() method is used to establish a
connection to a database.
• It uses a username, password, and a jdbc url to establish a
connection to the database and returns a connection object.
• A jdbc Connection represents a session/connection with a specific
database. Within the context of a Connection, SQL, PL/SQL
statements are executed and results are returned.
• An application can have one or more connections with a single
database, or it can have many connections with different
databases.
• A Connection object provides metadata i.e. information about the
database, tables, and fields. It also contains methods to deal with
transactions.
JDBC URL Syntax::
jdbc: <subprotocol>: <subname>
•Each driver has its own subprotocol
•Each subprotocol has its own syntax for the
source
• Example: For example, we're using the jdbc odbc
subprotocol, so the DriverManager knows to use
the sun.jdbc.odbc.JdbcOdbcDriver.
try{
Connection dbConnection =
DriverManager.getConnection(url, "loginName",
"Password");
} catch( SQLException x ){
System.out.println( "Couldn't get connection!" );
}
Creating a jdbc Statement object,
Statement statement =
dbConnection.createStatement();