Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
JDBC
interfeisa
realizēšanai
izmantošana
SQL
komandu
SQL Java JDBC DB
2
JDBC API komponentes
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.
3
JDBC API programmu paketes
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.).
4
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.
5
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ā
saprot 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;%CLASSP
ATH%
Make sure following environment variables are set as described below:
1) JAVA_HOME: This environment variable should point to the
directory where you installed the JDK, e.g.
C:\Program Files\Java\jdk1.5.0
D:\oracle\product\10.2.0\db_1\jdk
2) CLASSPATH: This environment variable should have appropriate
paths set, e.g.
C:\Program Files\Java\jdk1.5.0_20\jre\lib
D:\oracle\product\10.2.0\db_1\jdk\jre\lib
3) PATH: This environment variable should point to appropriate JRE bin,
e.g.
C:\Program Files\Java\jre1.5.0_20\bin
D:\oracle\product\10.2.0\db_1\jdk\jre\bin
6
JDBC interfeisa izmantošanas pamatdarbības
1. JDBC interfeisa programmu pakešu imports (nepieciešamo JDBC
Java klašu piesaiste).
2. JDBC dziņa (draivera) reģistrācija. Vēlamā draivera realizācija
tiek ielādēta operatīvajā atmiņā, lai varētu izpildīt JDBC
pieprasījumus (requests).
3. Datu bāzes URL norādīšana. Izmantojamās datu bāzes adreses
norādīšana.
4. Lietojuma un datu bāzes savienojuma objekta Connection
izveidošana. DriverManager objekta getConnection() metodes
izsaukums. Tas izveido savienojumu ar datu bāzi.
5. SQL komandas objekta (statement) izveidošana.
6. Vaicājuma izpilde un rezultāta ieguve (execute a query and return a
ResultSet object).
7. Iegūtā rezultāta apstrāde (process the ResultSet object).
8. Rezultāta un komandas objektu aizvēršana (close the ResultSet and
Statement objects).
7
JDBC izmantošanas pamatshēma
8
1. darbība. JDBC programmu pakešu imports
import java.sql.* ; // JDBC bibliotēka.
import oracle.jdbc.driver.* ; // Bibliotēka ar datu bāzes draiveriem.
9
Lai savienotu Java lietojuma programmu ar datu bāzes
sistēmu, tiek realizētas sekojošas darbības
1. Tiek veikta Oracle, Java un JDBC programmu ietvaru
iestatīšana.
2. Tiek veikts nepieciešamo JDBC klašu imports (JDBC un
Oracle).
3. Konkrētās datu bāzes sistēmas savienojuma nodrošināšanas
programmas (database driver) piesaiste un reģistrēšana.
4. Savienojuma objekta (connection object) izveidošana ar
savienojuma nodrošināšanas programmas palīdzību.
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.
10
2. darbība. JDBC draivera reģistrēšana un savienojuma
objekta izveidošana.
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.
11
JDBC Thin Client
The JDBC Thin client is a pure Java, Type IV driver. It is lightweight and easy to install. It provides
high performance, comparable to the performance provided by the JDBC Oracle Call Interface
(OCI) driver. The JDBC Thin driver is written entirely in Java, and therefore, it is platformindependent. Also, this driver does not require any additional Oracle software on the client-side.
The JDBC Thin driver communicates with the server using TTC, a protocol developed by Oracle to
access data from Oracle Database. It can be used for application servers as well as for applets. The
driver allows a direct connection to the database by providing an implementation of TCP/IP that
implements Oracle Net and TTC on top of Java sockets. Both of these protocols are lightweight
implementation versions of their counterparts on the server. The Oracle Net protocol runs over
TCP/IP only.
The JDBC Thin driver can be used on both the client-side and the server-side. On the client-side,
drivers can be used in Java applications or Java applets that run either on the client or in the middle
tier of a three-tier configuration. On the server-side, this driver is used to access a remote Oracle
Database instance or another session on the same database.
Additional Features Supported
The JDBC Thin driver supports all standard JDBC features. The JDBC Thin driver also provides
support for the following additional features:
Support for Applets
Default Support for Native XA
12
2. darbība. JDBC draivera reģistrēšana un savienojuma
objekta
izveidošana.
Klases
DriverManager
izmantošana
Datu bāzes draivera programmas reģistrācija ir process kurā draivera
klase tiek ielādēta atmiņā, lai tā varētu realizēt JDBC interfeisu.
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
static Connection conn = null;
conn = DriverManager.getConnection("jdbc:oracle:thin:@dators:
1521:BAZE", "system", "janis");
Driver DBdzinis = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(DBdzinis);
static Connection conn = null;
conn = DriverManager.getConnection("jdbc:oracle:thin:@dators:
1521:BAZE", "system", "janis");
Connection conn =
DriverManager.getConnection("jdbc:default:connection:");
Connection conn =
DriverManager.defaultConnection();
Ja kļūda – SQLException;
However, the server-side internal JDBC driver runs within a default session and
a default transaction context. As a result, you are already connected to the database,
and all your SQL operations are part of the default transaction. You need not register
the driver because it comes preregistered.
13
2. darbība. JDBC draivera reģistrēšana un savienojuma
objekta izveidošana. Oracle Call Interface (OCI)
draivera izmantošana (klases forName lietošana)
Class.forName ("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection
("jdbc:oracle:oci8:@localhost", "system", "janis");
Bet var arī:
Class.forName ("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@//localhost:1521/BAZE", "system", "janis");
Ja kļūda – ClassNotFoundException.
Oracle's JDBC Thin driver uses Java sockets to connect directly to Oracle.
It provides its own TCP/IP version of Oracle's SQL*Net protocol. Because
it is 100% Java, this driver is platform independent and can also run from a
Web Browser (applets).
14
2. darbība. Savienojuma ar datu bāzes sistēmu
izveidošana.
Oracle KPRB draiveris
Connection conn =
(new oracle.jdbc.OracleDriver()).defaultConnection();
Oracle's JDBC KPRB driver is mainly used for writing Java stored procedures,
triggers and database JSPs. It uses the default/ current database session and thus
requires no additional database username, password or URL.
Remember not to close the default Connection. Closing the default connection
might throw an exception in future releases of Oracle.
jdbc:oracle:kprb
jdbc:default:connection
jdbc:oracle:kprb:
jdbc:default:connection:
15
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.
16
2. darbība. OracleDataSource klases izmantošana
savienojuma veidošanai ar datu bāzes sistēmu
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:kprb");
Connection conn = ods.getConnection();
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:default:connection");
Connection conn = ods.getConnection();
ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:@//server.local:1521/prod");
ods.setUser("scott");
ods.setPassword("tiger");
17
2. darbība. Datu bāzes adreses (URL) norādīšana
Izmantojot DriverManager.getConnection() metodi var izmantot trīs
variantus datu bāzes URL norādei:
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
URL formāts
jdbc:mysql://hostname/
MySQL
com.mysql.jdbc.Driver
databaseName
jdbc:oracle:thin:@hostname:port
ORACLE oracle.jdbc.driver.OracleDriver
Number:databaseName
COM.ibm.db2.jdbc.net.DB2Driv jdbc:db2:hostname:port
DB2
er
Number/databaseName
jdbc:sybase:Tds:hostname: port
Sybase
com.sybase.jdbc.SybDriver
Number/databaseName
DBVS
JDBC dziņa nosaukums
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
variants
- Rekomendētais jaunais pieraksta
18
3. darbība. Priekšraksta (statement) jeb komandas
objekta izveidošana. Statement klase
Statement klase. Lieto SQL komandām, kurām nav IN tipa
parametru.
String sql = "DROP " + object_type + " " + object_name;
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql);
String sql = "SELECT COUNT(*) FROM " + tabName;
int rows = 0;
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(sql);
while (rset.next()) {rows = rset.getInt(1);}
A ResultSet object contains SQL query results, that is, the rows that meet the search condition.
You can use the next() method to move to the next row, which then becomes the current row. You
can use the getXXX() methods to retrieve column values from the current row.
19
3. darbība. Priekšraksta (statement) vai komandas
objekta izveidošana. PreparedStatement klase
PreparedStatement klase. Lieto SQL komandām, kurām ir IN tipa
parametri un kuras tiek izpildītas atkārtoti. Notiek pārkompilācijas.
String sql = "DELETE FROM dept WHERE deptno = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, deptID);
pstmt.executeUpdate();
20
3. darbība. Priekšraksta (statement) vai komandas
objekta izveidošana. CallableStatement klase
CallableStatement lieto datu bāzes serverī glabājamo funkciju un
procedūru izsaukšanai. Var būt IN un OUT tipa parametri.
// parameterless stored procedure
CallableStatement cstmt = conn.prepareCall("{CALL proc}");
// stored procedure
CallableStatement cstmt = conn.prepareCall("{CALL proc(?,?)}");
// stored function
CallableStatement cstmt = conn.prepareCall("{? = CALL
func(?,?)}");
Important Points. When developing JDBC applications that access stored procedures, you must
consider the following:
1) Each Oracle JVM session has a single implicit native connection to the Database session in
which it exists. This connection is conceptual and is not a Java object. It is an inherent aspect of the
session and cannot be opened or closed from within the JVM.
2) The server-side internal JDBC driver runs within a default transaction context. You are already
connected to the database, and all your SQL operations are part of the default transaction. Note that
this transaction is a local transaction and not part of a global transaction, such as that implemented
by Java Transaction API (JTA) or Java Transaction Service (JTS).
3) Statements and result sets persist across calls and their finalizers do not release database cursors.
To avoid running out of cursors, close all statements and result sets after you have finished using
them. Alternatively, you can ask your DBA to raise the limit set by the initialization parameter,
OPEN_CURSORS.
4) The server-side internal JDBC driver does not support auto-commits. As a result, your
application must explicitly commit or roll back database changes.
5) You cannot connect to a remote database using the server-side internal JDBC driver. You can
connect only to the server running your Java program. For server-to-server connections, use the
server-side JDBC Thin driver. For client/server connections, use the client-side JDBC Thin or
JDBC Oracle Call Interface (OCI) driver.
6) Typically, you should not close the default connection instance because it is a single instance that
can be stored in multiple places, and if you close the instance, each would become unusable. If it is
closed, a later call to the OracleDriver.defaultConnection method gets a new, open instance. The
OracleDataSource.getConnection method returns a new object every time you call it, but, it does
not create a new database connection every time. They all utilize the same implicit native
connection and share the same session state, in particular, the local transaction.
21
4. darbība. SQL komandas izpilde: execute-Query(),
executeUpdate(), 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");
22
5. darbība. Iegūto rezultātu - ResultSet objekta apstrāde
while (rezultats.next()) {
String nos = rezultats.getString("NOS");
int num = rezultats.getInt("NUM");
… }
NUMBER
DATE
VARCHAR2
BLOB
CLOB
ARRAY
Structured type
REF
getInt()
getDate()
getString()
getBlob()
getClob()
getArray()
getObject()
getRef()
6. darbība. Piesaistīto resursu atbrīvošana (aizvēršana)
rezultats.close();
komanda.close();
savienojums.close(); (Jāuzmanās !!!)