0% found this document useful (0 votes)
44 views12 pages

Java Database Connectivity: Possibly Remote

The document discusses connecting to a database from a Java program using Java Database Connectivity (JDBC). It outlines the key steps: 1) loading the appropriate JDBC driver, 2) connecting to the database server by establishing a connection, 3) executing SQL commands or queries using Statement objects to interact with the database, and 4) closing the connection when finished. The classes involved include DriverManager, Connection, Statement, and ResultSet.

Uploaded by

Rajesh Reddy
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views12 pages

Java Database Connectivity: Possibly Remote

The document discusses connecting to a database from a Java program using Java Database Connectivity (JDBC). It outlines the key steps: 1) loading the appropriate JDBC driver, 2) connecting to the database server by establishing a connection, 3) executing SQL commands or queries using Statement objects to interact with the database, and 4) closing the connection when finished. The classes involved include DriverManager, Connection, Statement, and ResultSet.

Uploaded by

Rajesh Reddy
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Chapter 6

Java DataBase Connectivity

How to connect to a database from a Java program?


• Java does not provide a database system of its own
• but it can connect to already existing databases
• this is called ”Java Database Connectivity (JDBC)”.

possibly remote

JDBC Driver Database server


Java program

on the local on the local


machine machine

Database
6.1 Preliminaries

Make sure that


• the database already exists
• the Database Server is running (on our computer or on a remote com-
puter)
• we have permissions to the Database
• we have a network connection to the DB server or it is running locally.
73
6.2 The steps in detail

Loading the DB driver

2
Connecting to the DB
(username, password, ...)

3
Executing commands

"update" "query"

4
Closing connection

74
6.2.1 LOADING THE DRIVER

• Goal: loading the Driver (i.e. making it available for our program)
• What is a Driver: in general a .jar file (Java Archive) which can be
reached by the Java environment at run time (see later).
• Where to get the Driver from:
– names like pgjdbc1.jar, pgjdbc2.jar, jdbc7.1-1.1.jar.
– may be part of the installed Java environment
– may be part of the Database environment (comes with the install
package)
– from the Web: java.sun.com, from the Database’s site or from other
vendors.
• Important: you have to make the driver reachable by the Java envi-
ronment BEFORE running your Java program, i.e. you have to set up
the CLASSPATH. E.g. (for UNIX bash)

export CLASSPATH=.:pgjdbc1.jar

Example:
try {
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException c)
{
System.out.println("Database driver not found...");
}
• this loads the Driver class as part of the DriverManager class, used in
the next step
• the driver’s documentation gives the class name to use
• here we used the driver for PostgreSQL 7.2.2 and Java 1.1.8.
• there is a common driver called ”Open Database Connectivity (ODBC)”
which works for a lot of databases.

75
Other examples:
Class.forName("sun.jdbc.odbc.JdbcObdcDriver");
Class.forName("jdbc.DriverXYZ");
Class.forName("postgresql.Driver");
About Classes:
Class.forName:
java.lang.Object
|
+--- java.lang.Class

public static native Class forName(String className)


throws ClassNotFoundException
"Returns the Class object associated with the class with
the given string name. Given the fully-qualified name for
a class or interface, this method attempts to locate, load
and link the class. If it succeeds, returns the Class
object representing the class. If it fails, the method
throws a ClassNotFoundException."

76
6.2.2 CONNECTING TO THE DATABASE SERVER

• Goal: connecting to the DB server as a client, authentication.


• Assumption: we have a local or remote, database server and
• we have account on it (user name, password).
Example:
include java.sql.*
String url="jdbc:postgresql://twoquid.cs.kun.nl/test";
String user="Kees", pass="secret";
try {
Connection con=DriverManager.getConnection(url, user, pass);
} catch (SQLException s)
{
System.out.println("Couldn’t connect to database... " + url);
}
• you have to include the java.sql package (java.sql.*) because of the
class Connection.
• the method getConnection is used for setting up the properties of the
connection. one of its forms:
getConnection(String url, String user, String password)
where url has one of the forms:
jdbc:<database type>:<database>
-> jdbc:<database type>://<host>/<database>
jdbc:<database type>://<host>:<port>/<database>
• the <database type> is provided by your DB vendor.
• <host> is the name of the host where the DB server is running
• <database> is the name of the database you want to connect to.
• In our case

String url="jdbc:postgresql://twoquid.cs.kun.nl/test";

• you should get rights to connect (user name, password) BEFORE con-
necting (set it up at the server side).

77
• it is possible that the server needs a setting like: ”accept TCP/IP
connections”
• you should have an open port (set up the firewall for the server or
contact the server administrator). Check it BEFORE connecting.
About classes:
java.lang.Object
|
+--java.sql.DriverManager

public class DriverManager extends Object


(defined in: java.sql)
"The basic service for managing a set of JDBC drivers."
"A program can also explicitly load JDBC drivers at any time.
For example, the my.sql.Driver is loaded with the following
statement:
Class.forName("my.sql.Driver");
When the method getConnection is called, the DriverManager
will attempt to locate a suitable driver from amongst those
loaded at initialization and those loaded explicitly using
the same classloader as the current applet or application."
methods (e.g.):
static Connection getConnection(String url, Properties info)
throws SQLException
"Attempts to establish a connection to the given database URL."
static Connection getConnection(String url, String user, String password
throws SQLException
"Attempts to establish a connection to the given database URL."

78
public interface Connection
(defined in: java.sql)
"A connection (session) with a specific database. Within
the context of a Connection, SQL statements are executed
and results are returned."
methods (e.g.):
void close()
"Releases a Connection’s database and JDBC resources
immediately instead of waiting for them to be automatically
released."
Statement createStatement()
"Creates a Statement object for sending SQL statements to
the database." We will use it in the next step.
void commit()
"Makes all changes made since the previous commit/rollback
permanent and releases any database locks currently held by
the Connection."
boolean isClosed()
"Tests to see if a Connection is closed."
It has fields, too.
• database servers have generally a default port, for example PostgreSQL
uses the port number 5432. You don’t have to care about it: the driver
knows the default port number - or you should set up the server and
invoke the driver with the right port number.
• of course, a DB server handles usually several databases for ex. in a
sw. company one for helping in the person administration of the firm,
one for a project to a hospital, one for testing the database scalability,
etc. Every database may contain a lot of tables and relations between
them. Now we can connect to one of the databases.
• We have used the Java documentation for jdk1.2 . It might be different
from those for JEE2.

79
6.2.3 EXECUTING COMMANDS

• Goal: finally execute commands.


• They can be queries in SQL or updating commands like ”create table
...”.
• Java needs this distinction because the result has different forms: queries
result in a possibly infinite set while updating commands result only
in an indication whether the execution was succesful.
Example:
Statement stat=con.createStatement();
stat.executeUpdate("create table persons
(first varchar(15), last varchar(15));");
• we used con, the Connection object instantiated in step 2
• we can catch the possible Exceptions
• we could handle the result (return code).
Continuation of example:
stat=con.createStatement();
ResultSet res=stat.executeQuery("select * from persons;");
while (res.next())
{
System.out.println(res.getString(1)+" "+res.getString(2));
}
res.close();
• we need the ”while” statement because we do not know how many
rows we get back.
• now we can give commands and queries...
About classes:
public interface Statement
(defined in: java.sql)
"The object used for executing a static SQL statement
and obtaining the results produced by it.
Only one ResultSet per Statement can be open at any point
in time. herefore, if the reading of one ResultSet is
interleaved with the reading of another, each must have
80
been generated by different Statements. All statement
execute methods implicitly close a statement’s current
ResultSet if an open one exists. "
methods (e.g.):
ResultSet executeQuery(String sql)
"Executes a SQL statement that returns a single
ResultSet." ResultSet is discussed below.
"Returns: a ResultSet that contains the data produced by
the query; never null. Throws: SQLException - if a
database access error occurs"
int executeUpdate(String sql)
"Executes an SQL INSERT, UPDATE or DELETE statement."
"Returns: either the row count for INSERT, UPDATE or DELETE
or 0 for SQL statements that return nothing.
Throws: SQLException"
void close()
"Releases this Statement object’s database and JDBC resources
immediately instead of waiting for this to happen when it
is automatically closed."

public interface ResultSet


(defined in: java.sql)
"A ResultSet provides access to a table of data. A ResultSet object
is usually generated by executing a Statement.
A ResultSet maintains a cursor pointing to its current row of data.
Initially the cursor is positioned before the first row. The ’next’
method moves the cursor to the next row."
methods:
boolean next()
"Moves the cursor down one row from its current position."
String getString(int columnIndex)
"Gets the value of a column in the current row as a Java String."
String getString(String columnName)
"Gets the value of a column in the current row as a Java String."
int getInt(int columnIndex)
"Gets the value of a column in the current row as a Java int."

Remark: It has a lot of methods for all kind of contents and indexing on
column index, column name, etc. Cursor can be used on other ways, too.
It has fields, too.
81
6.2.4 CLOSING THE CONNECTION

• in fact unnecessary, because the DB server can recognise a lost con-


nection and close the connection and the database
item but the DB server doesn’t feel happy without it (”Unexpected
EOF on client connection” at the server side)
• if you would like to program in an elegant way, do it.
Example:
con.close();

6.3 A sample JDBC program

// Test program for JDBC


// for JDK 1.1.8 and PostgreSQL 7.7.2 on a remote machine
//
// To to before:
// * setting the CLASSPATH for the JDBC Driver
// * running DB server with authentication rights and
// possibility to connect (e.g. enabled port)

import java.sql.*;

class JDBCTester {

public static void main (String [] args)


{

// STEP 1: LOADING THE DRIVER MANAGER

try {
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException c)
{
System.out.println("Database driver not found...");
}

// STEP 2: CONNECTING TO THE DATABASE SERVER

82
String url="jdbc:postgresql://twoquid.cs.kun.nl/test";
String user="Kees", pass="secret";
try {
Connection con=DriverManager.getConnection(url, user, pass);

// STEP 3: EXECUTING COMMANDS

Statement stat=con.createStatement();
stat.executeUpdate("create table persons " +
"(first varchar(15), last varchar(15));");

stat=con.createStatement();
stat.executeUpdate("insert into persons " +
"(first, last) values (’Donald’, ’Duck’);");

stat=con.createStatement();
stat.executeUpdate("insert into persons " +
"(first, last) values (’George’, ’Bush’);");

stat=con.createStatement();
ResultSet res=stat.executeQuery("select * from persons;");
while (res.next())
{
System.out.println(res.getString(1)+ " " +res.getString(2));
}
res.close();

stat=con.createStatement();
stat.executeUpdate("drop table persons;");

// STEP 4: CLOSING THE CONNECTION

con.close();
}
// Closing is obligatory, otherwise we get a compiler error.
catch (SQLException s)
{
System.out.println("Couldn’t connect to database... " + url);
}

83
}

84

You might also like