JDBC

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

JDBC

The JDBC library includes APIs for each of the tasks commonly associated with database usage:

Making a connection to a database


Creating SQL statements
Executing that SQL queries in the database
Viewing & Modifying the resulting records

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.
The JDBC API provides the following interfaces and classes:

DriverManager:DriverManager is a class with static methods It is responsible for managing the set of Java Database Connectivity (JDBC) drivers that
are available for an application to use
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
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.

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection("jdbc:mysql://localhost/EMP",USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
JDBC Drivers Types:
JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the
implementation types into four categories, Types 1, 2, 3, and 4, which is explained below:

Type 1: JDBC-ODBC Bridge Driver:In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using ODBC requires
configuring on your system a Data Source Name (DSN) that represents the target database.
Type 2: JDBC-Native API:In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the database. These drivers typically
provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client
machine.
Type 3: JDBC-Net pure Java:In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use standard network sockets to
communicate with an middleware application server. The socket information is then translated by the middleware application server into the call format
required by the DBMS, and forwarded to the database server.
Type 4: 100% pure Java:In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database through socket connection. This is
the highest performance driver available for the database and is usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the client or server. Further, these drivers can be downloaded
dynamically. the preferred driver type is 4.
Thin drivers (comes under type 4 drivers) are completelywritten in java.You can connect to oracle without oracleclient installed on ur pc.
Thick drivers(comes under type 1 or i think 2,3 also)are notwritten completely in java.You need oracle client(like odbcdriver,jdbc-odbc bridge drivers etc)for
communicationbetween java program and oracle.

Statement

The object used for executing a static SQL statement and returning the results. Compilation required each time.

A SQL statement is precompiled and stored in a PreparedStatement object. This object can then be used to
PreparedStatement efficiently execute this statement multiple times. So no need to compile everytime. Prevents SQL injection. Allows
u to write dynamic and parametric query(? Is used as placeholder). Precompiled
CallableStatement

Use when you want to access database stored procedures. The CallableStatement interface can also accept runtime
input parameters.

Statement Interface : By default, only one ResultSet object per Statement object can be open at the same time. 3 methods to execute the query
Creating a Statement:
Statement stmt = null;
try {
con.createStatement();

}catch(SQLException sqlExc) {
}finally {
stmt.close();
}
boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this
method to execute SQL DDL statements or when you need to use truly dynamic SQL.
int executeUpdate(String SQL) : Returns the numbers of rows affected by the execution of the SQL statement. Use this method to execute
SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement.
ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a
SELECT statement.
PreparedStatement: Uses only IN parameter.
PreparedStatement pstmt =null;
try{
String SQL ="Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1,10);
pstmt.setString(2,15);
pstmt.executeUpdate();
}
catch(SQLException e){
...
}

finally{
...
The CallableStatement Objects:
Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the CallableStatement object which would be used to
execute a call to a database stored procedure. Uses all 3 parameters: IN, OUT, INOUT
Parameter

Description

IN

A parameter whose value is unknown when the SQL statement is created. You bind values to IN parameters
with the setXXX() methods.

OUT

A parameter whose value is supplied by the SQL statement it returns. You retrieve values from theOUT
parameters with the getXXX() methods.

INOUT

A parameter that provides both input and output values. You bind variables with the setXXX() methods and
retrieve values with the getXXX() methods.

The following code snippet shows how to employ the Connection.prepareCall() method to instantiate aCallableStatement object based on the preceding
stored procedure:
CallableStatement cstmt =null;
try{
String SQL ="{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
csmt.setInt(1,101);
csmt.setString(2,aadhu);
csmt.executeUpdate();
...
}
catch(SQLException e){
...
}
finally{
...
}
The String variable SQL represents the stored procedure, with parameter placeholders.
Using CallableStatement objects is much like using PreparedStatement objects. You must bind values to all parameters before executing the statement, or
you will receive an SQLException.
If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement object; use the setXXX() method that corresponds to
the Java data type you are binding.
When you use OUT and INOUT parameters you must employ an additional CallableStatement method, registerOutParameter(). The registerOutParameter()
method binds the JDBC data type to the data type the stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate getXXX() method. This method casts the retrieved
value of SQL type to a Java data type.
ResultSet
The java.sql.ResultSet interface represents the result set of a database query.
A ResultSet object maintains a cursor that points to the current row in the result set. The term "result set" refers to the row and column data contained in a
ResultSet object.
The methods of the ResultSet interface can be broken down into three categories:

Navigational methods: used to move the cursor around.


Get methods: used to view the data in the columns of the current row being pointed to by the cursor.
Update methods: used to update the data in the columns of the current row. The updates can then be updated in the underlying database as well.

The cursor is movable based on the properties of the ResultSet. These properties are designated when the corresponding Statement that generated the
ResultSet is created.
Methods: next(), first(), getInt(empId), getString(), isFirst(),last(),previous() etc
JDBC provides following connection methods to create statements with desired ResultSet:

createStatement(int RSType, int RSConcurrency);


prepareStatement(String SQL, int RSType, int RSConcurrency);
prepareCall(String sql, int RSType, int RSConcurrency);

The first argument indicate the type of a ResultSet object and the second argument is one of two ResultSet constants for specifying whether a result set is
read-only or updatable.
Resultsets are of 3 types.
Forward-only This type of result set can make the traversal for rows only in the forward direction and non-scrollable.
Scroll-insensitive Scroll-insensitive result set are not capable for scrolling. That means the cursor can move in only one direction. When the result set is open,
any change to the database table will not reflect.
Scroll-sensitiveUnlike Scroll-insensitive, the Scroll-sensitive result set is capable to move the cursor in bidirectional. It also enables the changes done to the
database tables when open

SQL
Sample table with all Constraints:
CREATE TABLE CUSTOMERS(
ID
INT
NOT NULL,
NAME VARCHAR (20)
NOT NULL UNIQUE,
AGE INT
NOT NULL NOT NULL CHECK (AGE >=18),
ADDRESS CHAR (25) ,
SALARY
DECIMAL (18, 2)DEFAULT 5000.00,
PRIMARY KEY (ID)
);
CREATE TABLE ORDERS (
ID
INT
NOT NULL,
DATE
DATETIME,
CUSTOMER_ID INT references CUSTOMERS(ID), //foreign key
AMOUNT
double,
PRIMARY KEY (ID)
);
DROP TABLE CUSTOMERS;
INSERT INTO CUSTOMERS (ID,NAME)VALUES (1, Vijay);
INSERT INTO CUSTOMERS VALUES (7, Vijay);
INSERT INTO first_table_name [(column1, column2, ... columnN)]
SELECT column1, column2, ...columnN
FROM second_table_name
[WHERE condition];
SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000 AND age < 25;
UPDATE CUSTOMERSSET ADDRESS = 'Pune'WHERE ID = 6;
DELETE FROM CUSTOMERSWHERE ID = 6;
DELETE FROM CUSTOMERS;
Constraints: Constraints are the rules enforced on data columns on table. These are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the database.

NOT NULL Constraint: Ensures that a column cannot have NULL value.
DEFAULT Constraint: Provides a default value for a column when none is specified.
UNIQUE Constraint: Ensures that all values in a column are different.
PRIMARY Key: Uniquely identified each rows/records in a database table.
FOREIGN Key: Uniquely identified a rows/records in any another database table.
CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain conditions.
INDEX: Use to create and retrieve data from the database very quickly.

Dropping Constraints:Any constraint that you have defined can be dropped using the ALTER TABLE command with the DROP CONSTRAINT option.
ALTER TABLE EMPLOYEES DROP CONSTRAINT EMPLOYEES_PK;

Table Alias:
SELECT C.ID, C.NAME, C.AGE, O.AMOUNT
FROM CUSTOMERS AS C, ORDERS AS O
WHERE C.ID = O.CUSTOMER_ID;
Index: The INDEX is used to create and retrieve data from the database very quickly. Index can be created by using single or group of columns in a table.
When index is created, it is assigned a ROWID for each row before it sorts out the data. Indexes are special lookup tables that the database search engine can
use to speed up data retrieval. Simply put, an index is a pointer to data in a table
CREATE TABLE CUSTOMERS(
ID
INT
NOT NULL,
NAME VARCHAR (20)
NOT NULL,
AGE INT
NOT NULL,
ADDRESS CHAR (25),
SALARY
DECIMAL (18,2),
PRIMARY KEY (ID)
);
CREATE INDEX idx_ageON CUSTOMERS ( AGE );
ALTER TABLE CUSTOMERS

DROP INDEX idx_age;

Joins:
The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using
values common to each.
JOIN Types:
INNER JOIN: returns rows when there is a match in both tables.Equi join( join with =) &Non-Equi join (Theta join ->,<,>= etc)
OUTER JOIN:
LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.
FULL JOIN: returns rows when there is a match in one of the tables.
SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.
CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.
Operators:
Like Operator (wildcards used are % - 0,1 or more characters and _ exactly one )
SELECT FROM table_nameWHERE column LIKE '%XXXX%'
SELECT FROM table_nameWHERE column LIKE 'XXXX_'
ORDER BY Asc or desc order
SELECT * FROM CUSTOMERSORDER BY NAME DESC;

DISTINCT eliminates all duplicate records


SELECT DISTINCT SALARY FROM CUSTOMERS

ORDER BY SALARY;

GROUP BY:GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups.
SELECT NAME, SUM(SALARY) FROM CUSTOMERS GROUP BY NAME;
SELECT COUNT(1) from customers group by empId will take only one column to count the total records
SELECT COUNT(*) from customers group by empId takes all the column values and counts the records
HAVING:The HAVING clause enables you to specify conditions that filter which group results appear in the final results.
SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
GROUP BY age
HAVING COUNT(age)>=2;
UNION/UNION ALL:
UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows. Two tables column count
should match.
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows.
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION ALL
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
IS NULL/IS NOT NULL operator
SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
WHERE SALARY IS NOT NULL;
SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
WHERE SALARY IS NULL;

ALTER TABLE :
The basic syntax of ALTER TABLE to add a new column in an existing table is as follows:
ALTER TABLE table_name ADD column_name datatype;
The basic syntax of ALTER TABLE to DROP COLUMN in an existing table is as follows:

ALTER TABLE table_name DROP COLUMN column_name;


The basic syntax of ALTER TABLE to change the DATA TYPE of a column in a table is as follows:
ALTER TABLE table_name MODIFY COLUMN column_name datatype;
The basic syntax of ALTER TABLE to add a NOT NULL constraint to a column in a table is as follows:
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows:
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);
The basic syntax of ALTER TABLE to ADD CHECK CONSTRAINT to a table is as follows:
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);
The basic syntax of ALTER TABLE to ADD PRIMARY KEY constraint to a table is as follows:
ALTER TABLE table_name
ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);
The basic syntax of ALTER TABLE to DROP CONSTRAINT from a table is as follows:
ALTER TABLE table_name
DROP CONSTRAINT MyUniqueConstraint;

TRUNCATE: TRUNCATE TABLE command is used to delete complete data from an existing table. Retains table structure. Truncate is a DDL. Table level
deletion at one stretch. Cannot be rolled back since all DDLs are autocommit. Truncate is faster than DELETE
DELETE : Retains table structure, only the data is removed. Delete is DML. Deletion happens row by row. Can be rolled back if not commited.
DROP TABLE command to delete complete table but it would remove complete table structure form the database and you would need to re-create this table
once again if you wish you store some data.
VIEWS: Projection of tables.
CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS;
SELECT * FROM CUSTOMERS_VIEW;
CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS
WHERE age IS NOT NULL
WITH CHECK OPTION;
The WITH CHECK OPTION in this case should deny the entry of any NULL values in the view's AGE column, because the view is defined by data that does not
have a NULL value in the AGE column.
(You can also insert/update/delete records in a view)
UPDATE CUSTOMERS_VIEW
SET AGE =35
WHERE name='Ramesh';
DELETE FROM CUSTOMERS_VIEW
WHERE age =22;
DROP VIEW CUSTOMERS_VIEW;
SEQUENCE

CREATE SEQUENCE sequence_name


MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
NOCACHE //generated when required and not at once
NOCYCLE;
INSERT INTO suppliers
(supplier_id, supplier_name)
VALUES
(supplier_seq.NEXTVAL, 'Kraft Foods');
TRIGGERS:A trigger is a named program unit that is stored in the database and fired (executed) in response to a specified event.

CREATE OR REPLACE TRIGGER drop_trigger


BEFORE DROP ON hr.SCHEMA
BEGIN
RAISE_APPLICATION_ERROR (
num => -20000,
msg => 'Cannot drop object');
END;
STOREDPROCEDURE:Stored procedures are compiled once and stored in executable form, so procedure calls are quick and efficient. Executable code is
automatically cached and shared among users. This lowers memory requirements and invocation overhead.
By grouping SQL statements, a stored procedure allows them to be executed with a single call.
CREATEORREPLACEPROCEDURE procPrintHelloWorld
IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello World!');
END;
/
Run it
EXEC procPrintHelloWorld;

You might also like