0% found this document useful (0 votes)
50 views13 pages

Java Group 1

The document discusses connecting to databases using JDBC in Java. It provides steps to connect to Oracle, MySQL and Apache Derby databases, including specifying the driver, connection URL, username and password. It also discusses the JDBC architecture and components.

Uploaded by

Prince Mavhura
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
50 views13 pages

Java Group 1

The document discusses connecting to databases using JDBC in Java. It provides steps to connect to Oracle, MySQL and Apache Derby databases, including specifying the driver, connection URL, username and password. It also discusses the JDBC architecture and components.

Uploaded by

Prince Mavhura
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 13

MIDLANDS STATE UNIVERSITY

FACULTY OF SCIENCE AND TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION SYSTEMS

HCS 406: OBJECT ORIENTED PROGRAMMING II


LEVEL 4.2
GROUP 1 PRESENTATION

NAME SURNAME REG NUMBER MODE OF ENTRY


TAKUDZWA CHINYANGA R165919A PDP
TICHAONA K ZAMBUKO R167556N PDP
LOUIS MATSIKA R167646Y PDP
VINCENT MATEMERA R163600V PDP
ALEC NTUWANA R165267H PDP

1. JDBC ARCHITECTURE
The JDBC API supports both two-tier and three-tier processing models for database access
but in general, JDBC Architecture consists of two layers −
 JDBC API: This provides the application-to-JDBC Manager connection.
 JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.

The JDBC driver manager ensures that the correct driver is used to access each data source.
The driver manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases.

Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −
Common JDBC Components

The JDBC API provides the following interfaces and classes −


 DriverManager: This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using
communication sub protocol. The first driver that recognizes a certain subprotocol
under JDBC will be used to establish a database Connection.
 Driver: This interface handles the communications with the database server. You
will interact directly with Driver objects very rarely. Instead, you use Driver
Manager objects, which manages objects of this type. It also abstracts the details
associated with working with Driver objects.
 Connection: This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication with
database is through connection object only.
 Statement: You use objects created from this interface to submit the SQL statements
to the database. Some derived interfaces accept parameters in addition to executing
stored procedures.
 ResultSet: These objects hold data retrieved from a database after you execute an
SQL query using Statement objects. It acts as an iterator to allow you to move
through its data.
 SQLException: This class handles any errors that occur in a database application

The JDBC API supports both two-tier and three-tier processing models for database access.
Figure 1: Two-tier Architecture for Data Access.

In the two-tier model, a Java application talks directly to the data source. This requires a
JDBC driver that can communicate with the particular data source being accessed. A user's
commands are delivered to the database or other data source, and the results of those
statements are sent back to the user. The data source may be located on another machine to
which the user is connected via a network. This is referred to as a client/server configuration,
with the user's machine as the client, and the machine housing the data source as the server.
The network can be an intranet, which, for example, connects employees within a
corporation, or it can be the Internet.

In the three-tier model, commands are sent to a "middle tier" of services, which then sends
the commands to the data source. The data source processes the commands and sends the
results back to the middle tier, which then sends them to the user. MIS directors find the
three-tier model very attractive because the middle tier makes it possible to maintain control
over access and the kinds of updates that can be made to corporate data. Another advantage is
that it simplifies the deployment of applications. Finally, in many cases, the three-tier
architecture can provide performance advantages. Figure 2: Three-tier Architecture for Data
Access.
Until recently, the middle tier has often been written in languages such as C or C++, which
offer fast performance. However, with the introduction of optimizing compilers that translate
Java bytecode into efficient machine-specific code and technologies such as Enterprise
JavaBeans™, the Java platform is fast becoming the standard platform for middle-tier
development. This is a big plus, making it possible to take advantage of Java's robustness,
multithreading, and security features.

With enterprises increasingly using the Java programming language for writing server code,
the JDBC API is being used more and more in the middle tier of a three-tier architecture.
Some of the features that make JDBC a server technology support for connection pooling,
distributed transactions, and disconnected row sets. The JDBC API is also what allows access
to a data source from a Java middle tier.
2 STEPS IN CONNECTING TO AT LEAST 3 DATABASES

Java Database Connectivity with Oracle


To connect java application with the oracle database, we need to follow 5 following steps. In
this example, we are using Oracle 10g as the database. So we need to know following
information for the oracle database:
1. Driver class: The driver class for the oracle database is
oracle.jdbc.driver.OracleDriver
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the
database, thin is the driver, localhost is the server name on which oracle is running,
we may also use IP address, 1521 is the port number and XE is the Oracle service
name. You may get all this information from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle
database.
5. step5 close the connection   

1. import java.sql.*;  
2. class OracleCon{  
3. public static void main(String args[]){  
4. try{  
5. //step1 load the driver class  
6. Class.forName("oracle.jdbc.driver.OracleDriver");  
7.   
8. //step2 create  the connection object  
9. Connection con=DriverManager.getConnection(  
10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
11.   
12. //step3 create the statement object  
13. Statement stmt=con.createStatement();  
14.   
15. //step4 execute query  
16. ResultSet rs=stmt.executeQuery("select * from emp");  
17. while(rs.next())  
18. System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
19.   
20. //step5 close the connection object  
21. con.close();  
22.   
23. }catch(Exception e){ System.out.println(e);}  
24.   
25. }  
26. }  

CONNECT TO MYSQL

To connect Java application with the MySQL database, we need to follow 5 following steps.

1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.


2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/test where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address,
3306 is the port number and test is the database name. We may use any database, in
such case, we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.
5. Close connection
1.Connection to Apache Derby

Steps :

1. Installation of Derby

Download the latest Derby version from the Apache website http://db.apache.org/derby/.


Choose the bin distribution and extract this zip to a directory of your choice.

Also make the Derby tools available in your path:

Set the environment variable DERBY_HOME to the Derby installation directory

Add DERBY_HOME/bin to the "path" environment variable


2.1 Starting Derby in server mode

Use the following command in the command line to start the Derby network server (located
in the Derby installation directory/bin). On Microsoft Windows it is possible to use the .bat
version.

startNetworkServer

This will start the network server which can serve an unlimited number of databases. By
default the server will be listening on port 1527 but this can be changed via the -poption.

startNetworkServer -p 3301

By default Derby will only accept connections from the localhost. To make the Derby server
accept connections also from other hosts use the following start command. Replace
"sampleserver.sampledomain.com" with the name or the IP of the server. The server will then
accept connections only from other servers as the localhost.

startNetworkServer -h sampleserver.sampledomain.com

If connections should be allowed from localhost and any other server use the following.

startNetworkServer -h 0.0.0.0

2.2 Connect to the Derby Server via Java

To connect to the network server via Java code you need to have the derbyclient.jar in your
classpath. The network connection string to this database is the IP address of the
server:portnumber. For example for a server which is running on localhost you can create a
new database via the following string.

jdbc:derby://localhost:1527/dbname;create=true
If you want to connect to an existing database you can use the following string.

jdbc:derby://localhost:1527/c:\temp\mydatabase

For example a small Java client might look like the following. This assumes that you have
already created a schema called a table users with the columns "name" and "number".
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class DerbyTest {


private Connection connect = null;
private Statement statement = null;
private ResultSet resultSet = null;

public DerbyTest() throws Exception {


try {

Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connect = DriverManager
.getConnection("jdbc:derby://localhost/c:/temp/db/FAQ/db");
PreparedStatement statement = connect
.prepareStatement("SELECT * from USERS");

resultSet = statement.executeQuery();
while (resultSet.next()) {
String user = resultSet.getString("name");
String number = resultSet.getString("number");
System.out.println("User: " + user);
System.out.println("ID: " + number);
}
} catch (Exception e) {
throw e;
} finally {
close();
}

private void close() {


try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {

}
}

public static void main(String[] args) throws Exception {


DerbyTest dao = new DerbyTest();
}

CONNECTING TO SQLite DATABASE

To use SQLite with java programs, you must have SQLite JDBC Driver and Java set up on
the system. Follow the steps given below:

o Download latest version of sqlite-jdbc-(VERSION).jar from sqlite-jdbc repository.


o Add the downloaded jar file to your class path.
o You can now connect to the SQLite database using java.

1. import java.sql.Connection;  
2. import java.sql.DriverManager;  
3. import java.sql.SQLException;  
4.    
5. public class Connect {  
6.      /** 
7.      * Connect to a sample database 
8.      */  
9.     public static void connect() {  
10.         Connection conn = null;  
11.         try {  
12.             // db parameters  
13.             String url = "jdbc:sqlite:C:/sqlite/JTP.db";  
14.             // create a connection to the database  
15.             conn = DriverManager.getConnection(url);  
16.               
17.             System.out.println("Connection to SQLite has been established.");  
18.               
19.         } catch (SQLException e) {  
20.             System.out.println(e.getMessage());  
21.         } finally {  
22.             try {  
23.                 if (conn != null) {  
24.                     conn.close();  
25.                 }  
26.             } catch (SQLException ex) {  
27.                 System.out.println(ex.getMessage());  
28.             }  
29.         }  
30.     }  
31.     /** 
32.      * @param args the command line arguments 
33.      */  
34.     public static void main(String[] args) {  
35.         connect();  
36.     }  
37. }  

You might also like