+ All Categories
Home > Technology > JDBC Java Database Connectivity

JDBC Java Database Connectivity

Date post: 17-Jan-2015
Category:
Upload: ranjan-kumar
View: 1,147 times
Download: 1 times
Share this document with a friend
Description:
Jdbc Java Database Connectivity
Popular Tags:
24
JDBC (Java Database Connectivity)
Transcript
Page 1: JDBC Java Database Connectivity

JDBC (Java Database Connectivity)

Page 2: JDBC Java Database Connectivity

There are 4 different types of JDBC drivers: JDBC-ODBC Bridge drivers (follows ODBC standards) Partly Java – Partly Native (this does not use any standards) Pure Java – Net Protocol Drivers Pure Java Drivers (also called Type4Drivers, most popular

one)

Important Classes:

DriverManager Driver Connection Statement ResultSet

Page 3: JDBC Java Database Connectivity

1) How to get the database connection?

There are two ways to get the database connection.

1) First is to load the the Driver using Class.forName() and use the DriverManager.getConnection().

2) Second is to use the DataSource to get the connection.

Page 4: JDBC Java Database Connectivity

Loading the driver:

Class.forName("DriverName"); e.g.Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

Getting the connection from DriverManager:

Connection connection = DriverManager.getConnection( "jdbc:microsoft:sqlserver://127.0.0.1\\ABCD:1443;” + “DatabaseName=JDBCDB","username", "password");

Getting the connection from the DataSource:

To make the data source we need to deploy the *-ds.xml file in the deploy directory of JBoss Application Server. You can find the sample *-ds.xml files for different databases in the jboss-eap-4.3/jboss-as/docs/examples/jca directory.

Page 5: JDBC Java Database Connectivity

<datasources> <local-tx-datasource>

<use-java-context>false</use-java-context> <jndi-name>PostgresDS</jndi-name> <connection-url>jdbc:postgresql://127.0.0.1:5432/ejb3db</connection-url> <!—- For ssl connection <connection- url>jdbc:postgresql://127.0.0.1:5432/ejb3db?ssl=true&amp;sslfactory=org.postg resql.ssl.NonValidatingFactory&amp;</connection-url> --> <driver-class>org.postgresql.Driver</driver-class> <user-name>x</user-name> <password>y</password> <!-- sql to call when connection is created. Can be anything, select 1 is valid for PostgreSQL <new-connection-sql>select 1</new-connection-sql> --> <!--pooling parameters--> <min-pool-size>50</min-pool-size> <max-pool-size>80</max-pool-size> <blocking-timeout-millis>5000</blocking-timeout-millis> <idle-timeout-minutes>1</idle-timeout-minutes> <!-- sql to call on an existing pooled connection when it is obtained from pool. Can be anything, select 1 is valid for PostgreSQL <check-valid-connection-sql>select 1</check-valid-connection-sql> --> <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml --> <metadata> <type-mapping>PostgreSQL 8.0</type-mapping> </metadata> </local-tx-datasource></datasources>

Sample *-ds.xml files for postgresql database :

Page 6: JDBC Java Database Connectivity

How to get Connection from the database?

InitialContext initialContext = new InitialContext();DataSource dataSource = (DataSource) initialContext.lookup("PostgresDS");Connection connection = dataSource.getConnection()

jndi.properties

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactoryjava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfacesjava.naming.provider.url=127.0.0.1:1099

Page 7: JDBC Java Database Connectivity

2) Setting up Tables:

Creating a Table:

String createTableCoffees = "CREATE TABLE COFFEES" + " (COF_NAM VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT," + " SALES INTEGER, TOTAL INTEGER)";

Creating JDBC Statements:executeQuery() is used for select statements (DQL). executeUpdate() is used to create or modify tables (DDL and DML).

Statement statement = connection.createStatement();statement.executeUpdate(createTableCoffees);

Page 8: JDBC Java Database Connectivity

Executing Statements:

executeQuery("SELECT statement...") executeUpdate("DDL and DML statements...")

Entering Data into a Table:

Statement statement = connection.createStatement(); statement.executeUpdate( "INSERT INTO COFFEES " + "VALUES('Colombian', 101, 7.99, 0, 0");

Getting Data from a Table:

ResultSet resultSet = statement.executeQuery("SELECT * FROM COFFEES");

Page 9: JDBC Java Database Connectivity

3) Updating Tables:String query = "SELECT COF_NAME, SALES FROM COFFEES “ +

" WHERE COF_NAME LIKE 'Colombian'";ResultSet resultSet = statement.executeQuery(query);while(rs.next()){

String s = resultSet.getString("COF_NAME"); int n = resultSet.getInt("SALES");

System.out.println(n + " ponds of " + s + " sold this week.");

}

String updateString = "UPDATE COFFEES " + "SET TOTAL = TOTAL + 75 " + "WHERE COF_NAME LIKE 'Colombian'";

statement.executeUpdate(updateString); String query = "SELECT COF_NAME, TOTAL FROM COFFEES" + "WHERE COF_NAME LIKE 'Colombian'"; ResultSet resultSet = statment.executeQuery(query); while(rs.next()) {

String s = rs.getString(1); int n = rs.getInt(2); System.out.println(n + " ponds of " + s +

" sold till date."); }

Page 10: JDBC Java Database Connectivity

4) Using PreparedStatement:

When to use PreparedStatment?

If you want to execute a Statement Object many times, it will normally reduce execution time to use a PreparedStatement object instead.

The main feature of a PreparedStatement object is that, unlike a Statement object it is given an SQL statement when it is created. The advantage of this is that in most cases, the SQL statement will be sent to the DBMS right away, where it will be compiled. As a result the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatemen’s SQL statement without having to compile it first.

Although PreparedStatement objects can be used for SQL statements with no parameters, you will probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statements and supply it with different values each time you execute it.

Page 11: JDBC Java Database Connectivity

Creating a PreparedStatement Object:

PreparedStatement updateSales = connection.preparedStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME" + " LIKE ? ");

Supplying values for PreparedStatement Parameters:

String updateString = "UPDATE COFFEES SET SALES=75 " + " WHERE COF_NAME LIKE 'Colombian'";

statement.executeUpdate(updateString);

PreparedStatement updateSales = connection.preparedStatement(

"UPDATE COFFEES SET SALES=? " + "WHERE COF_NAME LIKE ? ");

updateSales.setInt(1, 75); updateSales.setString(2, "Colombian"); updateSales.executeUpdate();

Code Fragment I:

Code Fragment II:

Page 12: JDBC Java Database Connectivity

Note: Once a parameter has been set with a value, it will retain that value until it is reset to another value or the method clearParameters is called.

updateSales.setInt(1, 100);updateSales.setString(2, "French_Roast"); updateSales.executeUpdate();updateSales.setString(2, "Espresso"); updateSales.executeUpdate();

Using a loop to set values:

PreparedStatement updateSales;String updateString = "update COFFEES "+

" set SALES = ? where COF_NAME like ?";updateSales = con.preparedStatement(updateString);int [] salesForWeek = {175, 150, 60, 155, 90};String [] coffees = ("Colombian", "French_Roast", "Colombian_Decaf", "French_Roast_Decaf");int len = coffees.length;for(int i=0; I < len; i++) {

updateSales.setInt(1, salesForWeek[i]);updateSales.setString(2, coffees[i]);updateSales.executeUpdate();

}

Page 13: JDBC Java Database Connectivity

Return values for the method executeUpdate:

* executeQuery returns a ResultSet object containing the results of the query sent to the DBMS, the return value for executeUpdate is an int that indicates how many rows of a table were updated.

updateSales.setInt(1, 50);updateSales.setString(2, "Espresso");int n = updateSales.executeUpdate();// n = 1 because one row had a change in it.

When the method executeUpdate is used to execute a DDL statement, such as in creating a table, it returns the int 0.

int n = executeUpdate(createTableCoffees); // n = 0

Note that when the return value for executeUpdate is 0, it can mean one of two things: 1) the statement executed was an update statement that affected zero rows, or 2) the statement executed was a DDL statement.

Page 14: JDBC Java Database Connectivity

String createSUPPLIERS = "create table SUPPLIERS " + "(SUP_ID INTEGER, SUP_NAME VARCHAR(40), " + "STREET VARCHAR(40), CITY VARCHAR(20), " +"STATE CHAR(2), ZIP CHAR(5))";

statement.executeUpdate(createSUPPLIERS);

statement.executeUpdate("insert int SUPPLIER values (101, " +"'Acme, Inc.', '99 Market Street', 'Groundsville', " +"'CA', '95199'");

statement.executeUpdate("insert int SUPPLIERS values (49, " +"'Superior Coffee', '1 Party Place', 'Mendocino', 'CA' "

+"'95460'");

statement.executeUpdate("Insert into SUPPLIERS value(150, " +"'The High Ground', '100 Coffee Lane', 'Meadows', 'CA‘,

'93966'";

ResultSet rs = statement.executeQuery("select * from SUPPLIERS");

String query = "SELECT COFFEES.COF_NAME " +"FROM COFFEES, SUPPLIERS " +"WHERE SUPPLIERS.SUP_NAME LIKE 'Acme, Inc.' " +"and SUPPLIER_ID = COFFEES.SUP_ID";

ResultSet rs = statement.executeQuery(query);System.out.println("Coffees bought from Acme, Inc.: ");while(rs.next()) {

String coffeeName = rs.getString("COF_NAME"); System.out.println(" " + coffeeName);}

5) Using Joins:

Page 15: JDBC Java Database Connectivity

6) Using Transactions:A transaction is a set of one or more statements that are executed together as a unit, so either all of the statements are executed or none of the statements is executed.

Disabling Auto-Commit Mode

connection.setAutoCommit(false);

where connection is an active connection.

Committing a TransactionOnce auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly.

connection.setAutoCommit(false);PreparedStatement updateSales = connection.preparedStatment(

"UPDATE COFFEES SET TOTAL = TOTAL + " + " ? WHERE COF_NAME LIKE ?");

updateTotal.setInt(1, 50); updateTotal.setString(2, "Colombian"); updateTotal.executeUpdate(); connection.commit(); connnection.setAutoCommit(true);

Page 16: JDBC Java Database Connectivity

Using Transaction to Preserve Data Integrity

Transaction isolation levels1) int TRANSACTION_NONE = 0;2) int TRANSACTION_READ_UNCOMMITTED = 1;3) int TRANSACTION_READ_COMMITTED = 2;4) int TRANSACTION_REPEATABLE_READ = 4;5) int TRANSACTION_SERIALIZABLE = 8;

void setTransactionIsolation(int level) throws SQLException; int getTransactionIsolation() throws SQLException;

When to call method rollback?

If you are trying to execute one or more statements in a transaction and get an SQLException, you should call the method rollback to abort the transaction and start the transaction all over again.

Page 17: JDBC Java Database Connectivity

7) Using Stored Procedures:In SQL

Create procedure SHOW_SUPPLIERSAsSelect SUPPLIERS.SUP_NAME, COFFEES.COF_NAME from SUPPLIERS, COFFEESwhere SUPPLIERS.SUP_ID = COFFEES.SUP_IDOrder by SUP_NAME

In Java (JDBC)

String createProcedure = “Create procedure SHOW_SUPPLIERS” +“as “ +“select SUPPLIER.SUP_NAME, COFFEES.COF_NAME ” +“from SUPPLIERS, COFFEES ” + “where SUPPLIER.SUP_ID = COFFEES.SUP_ID ” +“order by SUP_NAME”;

Statement stmt = con.createStatement();Stmt.executeUpdate(createProcedure);

Page 18: JDBC Java Database Connectivity

Steps Putting code in a class definition. Importing classes to make them visible

import java.sql.*; Using the main method. Using try and catch blocks. Retrieving Exceptions.

8) Creating Complete JDBC Applications:

Page 19: JDBC Java Database Connectivity

try {- - -- - -

} catch (SQLException ex) {System.err.println(“SQLException: ” +

ex.getMessage());}

try {Class.forName(“myDriverClassName”);

} catch (ClassNotFoundException ex) {System.err.println(“ClassNotFoundException: ” +

ex.getMessage());}

Page 20: JDBC Java Database Connectivity

Catching Exceptions

try {- - -- - -

} catch (SQLException ex) {System.err.println(“SQLException Caught”); while(ex != null){

System.out.println(“Message: “ +ex.getMessage());

System.out.println(“SQLState: “ +ex.getSQLState());

System.out.println(“ErrorCode: “ +ex.getErrorCode());

ex = ex.getNextException();System.out.println(“ ”);

}}

Page 21: JDBC Java Database Connectivity

Retrieving Warnings

SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned.

A warning can be reported on a # a connection object# a statement object (including PreparedStatment and

CallableStatement objects)# a ResultSet object

Each of these classes have a getWarnings method, which you mush invoke in order to see the first warning reported on the calling object. If getWarnings returns a warning, you can call the SQLWarning method getNextWarning on it to get any additional warnings. Executing a statement automatically clears the warnings from the previous statement, so they do not build up. This means, however that if you want to retrieve warnings reported on a statement you must do so before you execute another statement.

Page 22: JDBC Java Database Connectivity

Example

Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery(

“Select COF_NAME from COFFEES”);while(rs.next) {

String CoffeName = rs.getString(“COF_NAME”);System.out.println(“ Coffees available at the

Coffee Break: ”);System.out.println(“ ” + coffeeName);

SQLWarning warning = stmt.getWarnings();if(warning != null) {

System.out.println(“—Warning-”);while(warning != null){

System.out.println(“Message: ” +warning.getMessage());

System.out.println(“SQLState: ” +warning.getSQLState());

System.out.println(“Vendor Eror Code: ” + warning.getErrorCode());

warning = warning.getNextWarning();}

}---

Page 23: JDBC Java Database Connectivity

---SQLWarning warn = rs.getWarnings();if(warning != null) {

System.out.println(“-- Warning --”);while(warn != null) {

System.out.println(“Message: ” +warn.getMessage());

System.out.println(“SQLState: ” +warn.getSQLState());

System.out.println(“Vendor Error Code:” + warn.getErrorCode());

warn = warn.getNextWarning();}

}}

Page 24: JDBC Java Database Connectivity

The End


Recommended