Download JDBC draivera versijas noteikšana

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Entity–attribute–value model wikipedia , lookup

Microsoft Access wikipedia , lookup

Concurrency control wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Database wikipedia , lookup

Oracle Database wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Relational model wikipedia , lookup

Clusterpoint wikipedia , lookup

Database model wikipedia , lookup

Versant Object Database wikipedia , lookup

SQL wikipedia , lookup

PL/SQL wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Transcript
1
Lietojuma un datu bāzes sasaistes varianti izmantojot
JDBC interfeisu
Divu slāņu modelis (two-tier model)
Lietojumprogramma
JDBC interfeiss
Trīs slāņu modelis (three tier model)
Java programmēšana datu bāzes serverī
Datu bāzes sistēma
Java programma
JDBC interfeiss
Datu avots
2
What is JDBC
JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a
wide range of databases.
The JDBC library includes APIs for each of the tasks commonly associated with
database usage:
1) making a connection to a database;
2) creating SQL statements;
3) executing that SQL queries in the database;
4) viewing and modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that
allows for portable access to an underlying database. Java can be used to write
different types of executables, such as:
1) Java Applications;
2) Java Applets;
3) Java Servlets;
4) Java ServerPages (JSPs);
5) Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database
and take advantage of the stored data. JDBC provides the same capabilities as ODBC,
allowing Java programs to contain database-independent code.
3
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:
1) JDBC API: This provides the application-to-JDBC Manager connection;
2) 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.
4
Datu bāzes sistēmu interfeiss JDBC1
JDBC is a set of programming APIs that allows easy connection to a wide range
of databases from Java programs.
According to Sun Microsystems, the JDBC API contains two major sets of interfaces:
1) JDBC API for application writers;
2) the lower-level JDBC driver API for driver writers.
(http://java.sun.com/products/jdbc/overview.html.)
1
Mahmoud Parsian . JDBC Recipes: A Problem-Solution Approach. 2005. Ir fails.
5
JDBC Application Programming Interfeiss
JDBC API is defined by two packages:
1) java.sql provides the API for accessing and processing data stored in a data source
using the Java programming language. This package provides the foundation and
most commonly used objects such as Connection, ResultSet, Statement, and
PreparedStatement.
2) javax.sql provides the API for server-side data source access and processing from
the Java programming language. This package provides services for data objects
DataSource and RowSet.
6
Common JDBC Components
The JDBC API provides the following interfaces and classes:
1. DriverManager: This class manages a list of database drivers. Matches
connection requests from the java application with the proper database driver using
communication subprotocol. The first driver that recognizes a certain subprotocol
under JDBC will be used to establish a database Connection.
2. Driver: This interface handles the communications with the database server. You
will interact directly with Driver objects very rarely. Instead, you use DriverManager
objects, which manages objects of this type. It also abstracts the details associated
with working with Driver objects.
3. 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.
4. 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.
5. 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.
6. SQLException: This class handles any errors that occur in a database application.
7
java.sql programmu paketes galvenās klases
1. java.sql.DriverManager: The major task of the DriverManager class is to access
the JDBC drivers and create java.sql.Connection (database connection) objects.
2. java.sql.Connection: This interface represents a database connection. This is the
key for accessing most of the database objects (such as tables, columns, and so on).
3. java.sql.Statement: The Connection object creates Statement objects. You can use
the Statement object to execute SQL statements and queries, which produce
ResultSet objects (the result of executing SQL statements and queries).
4. java.sql.PreparedStatement: The Connection object creates PreparedStatement
(parameterized statement) objects. You can use the PreparedStatement object to
execute SQL statements and queries, which produce ResultSet objects (the result of
executing SQL statements and queries).
5. java.sql.CallableStatement: The Connection object creates CallableStatement
(statements used to execute stored procedures) objects. You can use the
PreparedStatement object to execute SQL statements and queries, which produce
ResultSet objects (the result of executing SQL statements and queries).
6. java.sql.ResultSet: The result of a SQL query is returned via a ResultSet object (a
table of data representing a database result set, which is usually generated by
executing a statement that queries the database).
7. SQLException: This class is an exception class that provides information on a
database access error or other errors.
8
java.sql.DriverManager klase un JDBC draiveri
java.sql.DriverManager ir savienojumu veidošanas klase (savienojumu rūpnīca
(connection factory)). Tā ir vienīgā klase, kura var izveidot savienojumus ar datu
bāzi. Katrs savienojums ir java.sql.Connection objekts.
Driver Manager klase izmanto JDBC dzini (driver) lai izveidotu savienojumu. Katra
datu bāzes sistēmas izstrādātāja firma (piemēram, Oracle, IBM, MS, Sybase) veic
apgādi ar nepieciešamajiem dziņiem.
JDBC dzinis ir Java klase, kura realizē java.sql.Driver interfeisu. Tā aprot kā SQL
vaicājumu vai DB glabājamās procedūras izsaukumu nodot datu bāzes sistēmai, lai tā
to izpildītu. Dziņi tiek noformēti kā *.jar vai *.zip tipa faili. Dziņa instalēšana nozīmē
viņa glabāšanas (atrašanās) vietas norādīšana operētājsistēmā (parametrs
CLASSPATH).
CLASSPATH=c:\\oracle\oracle\10.1.0\jdbc\lib\ojdbc14.jar;%CLASSPATH%
9
getConnection() metode
Connecting to your DBMS with the DriverManager class involves calling the
method DriverManager.getConnection. This method establishes a database
connection:
public Connection getConnection()
throws SQLException {
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", this.userName);
connectionProps.put("password", this.password);
if (this.dbms.equals("mysql")) {
conn = DriverManager.getConnection("jdbc:" + this.dbms + "://" +
this.serverName + ":" + this.portNumber + "/", connectionProps); }
else if (this.dbms.equals("derby")) {
conn = DriverManager.getConnection("jdbc:" + this.dbms + ":" +
this.dbName + ";create=true", connectionProps); }
System.out.println("Connected to database");
return conn; }
10
JDBC API Connection Object
The java.sql.Connection object represents a single logical database connection. You
use the Connection object for sending a set of SQL statements to the database server
and managing the committing or aborting (rollback) of those SQL statements. The
Connection object has the following capabilities:
1. Creates SQL statements.
2. Executes SQL queries, inserts, updates, and deletes.
3. Handles commits and rollbacks.
4. Provides metadata regarding the database connection.
11
JDBC realizēšana (JDBC programming steps)
1. Nepieciešamo pakešu imports (Import the required packages).
2. JDBC draivera reģistrēšana (Register the JDBC driver).
3. Savienojuma ar datu bāzi izveidošana (Open a connection to a
database).
4. Paziņojuma izveidošana (Create a Statement object).
5. Vaicājuma izpilde un rezultāta ieguve (Execute a query and return
a ResultSet object).
6. Rezultāta apstrāde (Process the ResultSet object).
7. Rezultāta un paziņojumavēršana objektu aizvēršana (Close the
ResultSet and Statement objects).
8. Savienojuma aizvēršana (Close the connection).
12
Pamatdarbības izmantojot JDBC draiverus
First it needs to establish a connection with the data source you want to use. A data
source can be a DBMS, a legacy file system, or some other source of data with a
corresponding JDBC driver. Typically, a JDBC application connects to a target data
source using one of two classes:
1. DriverManager: This fully implemented class connects an application to a data
source, which is specified by a database URL. When this class first attempts to
establish a connection, it automatically loads any JDBC 4.0 drivers found within the
class path. Note that your application must manually load any JDBC drivers prior to
version 4.0.
2. DataSource: This interface is preferred over DriverManager because it allows
details about the underlying data source to be transparent to your application. A
DataSource object's properties are set so that it represents a particular data source.
13
1. JDBC draivera ielāde un reģistrēšana. Tiek izmantotas komandas:
- DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
(ja kļūda –SQLException);
- ClassforName ("oracle.jdbc.OracleDriver");
(ja kļūda – ClassNotFoundException).
2. Savienojuma ar datu bāzi izveidošana. Tiek iegūts savienojuma objekts
no savienojumu rūpnīcas (connection factories). Lieto divas metodes:
1) draiveru pārvaldnieka (driver manager) izmantošana:
Connection savienojums
=DriverManager.getConnection(savienojums, lietotajs, parole);
Connection savienojums = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:BAZE","system","janis");
2) datu avota (data source) izmantošana:
OracleDataSource datuAvots= new OracleDataSource();
// JDBC parametru vērtību norādīšana
java.util.Properties ipasibas = new java.util.Properties();
...
ipasibas.put(….)
datuAvots.setURL(url);
Connection savienojums = datuAvots.getConnection(); ...
3. Priekšraksta (statement) objekta izveidošana (SQL komandas
norādīšanai).
Statement komanda=conn.createStatement();
4. SQL komandas izpilde: execute-Query(), executeUpdate(), and
execute().
ResultSet rezultats = komanda.executeQuery("select NOS from
FIRMAS");
int rowcount = komanda.executeUpdate("create table FIRMAS (NUM
number, NOS varchar2(20)");
int rowcount = komanda.executeUpdate(“delete from FIRMAS where
NUM = 7");
5. Iegūto rezultātu - ResultSet objekta apstrāde.
14
while (rezultats.next()) {
String nos = rezultats.getString("NOS");
int num = rezultats.getInt("NUM");
… }
NUMBER
getInt()
DATE
getDate()
VARCHAR2 getString()
BLOB
getBlob()
CLOB
getClob()
ARRAY
getArray()
Structured type
getObject()
REF
getRef()
6. Izmantoto, piesaistīto resursu atbrīvošana (aizvēšana).
rezultats.close();
komanda.close();
savienojums.close();
15
JDBC URL
A JDBC URL is the connect string used during database connection requests. It
specifies the JDBC driver type, authentication information, the database instance, the
host, the protocol, the port, service name, and so on. It contains either the complete
authentication information or partial information plus indirections (i.e., aliases) to
other mechanisms such as the TNSNAMES.ORA.
The Oracle JDBC URL format is as follows:
jdbc:oracle:<drivertype>:[<username>/<password>]@<database_specifier>
where:
<drivertype> = “thin” | “oci” | “kprb”
[<username>/<password>] = “<username>”/”<password>” | empty
jdbc:oracle:thin:@localhost:1521:orcl
jdbc:oracle:thin:@localhost:1521/myservice - Rekomendētais jaunais pieraksta
variants
16
JDBC draivera versijas noteikšana
(servera programma)
create or replace JAVA source named "JDBCVersija" as
import java.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.OracleDataSource;
class JDBCVersija{
public static void main (String args[ ])
throws SQLException {
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:JAVA_L/janis@DATORS:1521:BAZE");
Connection conn = ods.getConnection();
// Create Oracle DatabaseMetaData object
DatabaseMetaData meta = conn.getMetaData();
// gets driver info:
System.out.println("JDBC driver version is " + meta.getDriverVersion()); } ;
create or replace procedure JDBCVERSIJA
as language JAVA name 'JDBCVersija.main(java.lang.String[ ])';
SQL> SET SERVEROUTPUT ON
SQL> CALL dbms_java.set_output(2000);
SQL>call JDBCVERSIJA();
JDBC driver version is 10.1.0.2.0
select OBJECT_NAME, OBJECT_TYPE, STATUS
from USER_OBJECTS;
OBJECT_NAME
OBJECT_TYPE
STATUS
---------------------------------------------------------------------------JDBCVERSIJA
PROCEDURE
VALID
JDBCVersija
JAVA CLASS
VALID
JDBCVersija
JAVA SOURCE
VALID