Вы находитесь на странице: 1из 32

Programming in Java

UNIT-2
Java Database Programming

Lovely Professional University, Punjab


Lovely Professional University, Punjab
JDBC
 It is Java API for developing Java database applications is called JDBC.
 JDBC provides Java programmers with a uniform interface for accessing and manipulating a wide
range of relational databases.

Lovely Professional University, Punjab


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.

Lovely Professional University, Punjab


JDBC Driver Types
 JDBC-ODBC Bridge, plus ODBC driver (Type 1)
 JDBC methods -> Translate JDBC methods to ODBC methods -> ODBC to native
methods -> Native methods API

 Native-API, partly Java driver (Type 2)


 JDBC methods -> Map JDBC methods to native methods (calls to vendor library) -> Native methods API (vendor library)

 JDBC-Network driver (Type 3)


 JDBC methods -> Translate to Native API methods through TCP/IP network -> Native API methods

 Pure Java driver (Type 4)


 Java methods -> Native methods in Java
Developing Database Applications Using JDBC
 The JDBC API is a Java application program interface to generic SQL databases that enables Java
developers to develop DBMS-independent Java applications using a uniform interface.

 The JDBC API consists of classes and interfaces for establishing connections with databases,
sending SQL statements to databases, processing the results of the SQL statements, and
obtaining database metadata.

Lovely Professional University, Punjab


Steps during Execution
 The following steps are executed when running a JDBC application

 Import the necessary classes


 Load the JDBC driver
 Identify the database source
 Allocate a “connection” object (create)
 Allocate a “Statement” object (create)
 Execute a query using the “Statement” object
 Retrieve data from the returned “ResultSet” object
 Close the “ResultSet” object
 Close the “Statement” object
 Close the “Connection” object
JDBC Component Interaction

Driver Creates Creates Creates


Manager Connection Statement ResultSet

SQL

Driver
Establish
Link to DB Result
(tuples)

Database
Lovely Professional University, Punjab
Loading drivers
 An appropriate driver must be loaded using the statement shown below
before connecting to a database.
Class.forName("JDBCDriverClass");

Lovely Professional University, Punjab


Loading drivers
 Download mysqljdbc.jar from
 //www.javatpoint.com/example-to-connect-to-the-mysql-database
 Copy this jar file into ext folder of jre in java
 And set path
 Other jar files can be found from link given in Your Text book “Introduction to Programming ” by
Daniel Liang[Page No.1276, Chapter 37].

Lovely Professional University, Punjab


Setting path
 For temporary setting

 C:>set classpath C:\Program Files\Java\jre7\lib\ext\mysql-connector-java-5.0.8.-bin.jar;.;

 For permanent setting


 Set environment variable in advanced settings of computer
 Variable name=classpath and value=C:\Program Files\Java\jre7\lib\ext\mysql-connector-java-
5.0.8-bin.jar;.;

Lovely Professional University, Punjab


Establishing connections.
 Connection =DriverManager.getConnection(databaseURL);

Connection =
DriverManager.getConnection("jdbc:mysql://localhost/javabook", “root",
"tiger");
Lovely Professional University, Punjab
Commonly used methods of Connection interface

1) public Statement createStatement(): creates a statement object that can be used to


execute SQL queries.
2) public void setAutoCommit(boolean status): is used to set the commit status.By
default it is true.
4) public void commit(): saves the changes made since the previous commit/rollback
permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources
immediately.

Lovely Professional University, Punjab


Creating statements
 Statement = connection.createStatement();

 Executing statements
 statement.executeUpdate ("create table Temp (col1 char(5), col2 char(5))");

 ResultSet resultSet = statement.executeQuery("select firstName, mi, lastName from Student


where lastName = 'Smith'");

Lovely Professional University, Punjab


Commonly used methods of Statement
interface
The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns
the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be
create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple
results.
4) public int[] executeBatch(): is used to execute batch of commands.

Lovely Professional University, Punjab


Processing ResultSet
 while (resultSet.next())
System.out.println(resultSet.getString(1) + " " +resultSet.getString(2) + ". " +
resultSet.getString(3));

Lovely Professional University, Punjab


ResultSet Methods
 public boolean first() throws SQLException
Moves the cursor to the first row.
 public void last() throws SQLException
Moves the cursor to the last row.
 public boolean previous() throws SQLException
Moves the cursor to the previous row. This method returns false if the previous row is off
the result set.
 public boolean next() throws SQLException
Moves the cursor to the next row. This method returns false if there are no more rows in
the result set.

Lovely Professional University, Punjab


Viewing a Result Set
 The ResultSet interface contains dozens of methods for getting the data of the
current row.
 There is a get method for each of the possible data types, and each get method has
two versions −
 One that takes in a column name.
 One that takes in a column index.
 For example, if the column you are interested in viewing contains an int, you need to
use one of the getInt() methods of ResultSet −

Lovely Professional University, Punjab


Methods general form
 public int getInt(String columnName) throws SQLException
Returns the int in the current row in the column named columnName.
 public int getInt(int columnIndex) throws SQLException
Returns the int in the current row in the specified column index. The column index starts at 1,
meaning the first column of a row is 1, the second column of a row is 2, and so on.
Similarly, there are get methods in the ResultSet interface for each of the eight Java primitive
types, as well as common types such as java.lang.String, java.lang.Object, and java.net.URL.

Lovely Professional University, Punjab


PreparedStatement
 Most relational databases handles a JDBC / SQL query in four steps:
 Parse the incoming SQL query
 Compile the SQL query
 Plan/optimize the data acquisition path
 Execute the optimized query / acquire and return data

 A Statement will always proceed through the four steps above for each SQL query sent to the
database. A Prepared Statement pre-executes steps (1) - (3) in the execution process above.
Thus, when creating a Prepared Statement some pre-optimization is performed immediately.
The effect is to lessen the load on the database engine at execution time.

Lovely Professional University, Punjab


PreparedStatement
 The PreparedStatement interface, extending Statement, is used to
execute a precompiled SQL statement with or without parameters.
 Since the SQL statements are precompiled, they are efficient for
repeated executions.
 A PreparedStatement object is created using the prepareStatement
method in the Connection interface. For example, the following code
creates a PreparedStatement preparedStatement on a particular
Connection connection for an SQL insert statement:
 Statement preparedStatement = connection.prepareStatement("insert into Student (firstName,
mi, lastName) " +"values (?, ?, ?)");

Lovely Professional University, Punjab


PreparedStatement
 As a sub interface of Statement, the PreparedStatement interface inherits all the methods
defined in Statement.
 It also provides the methods for setting parameters in the object of PreparedStatement. These
methods are used to set the values for the parameters before executing statements or
procedures. In general, the set methods have the following name and signature:
setX(intparameterIndex,Xvalue);
 Where X is the type of the parameter, and parameter Index is the index of the parameter in the
statement.
 The index starts from 1.
 The following statements pass the parameters “Jack”, “A”, and “Ryan” to the placeholders for
firstName, mi, and lastName in PreparedStatement :
 preparedStatement.setString(1,"Jack");
 preparedStatement.setString(2,"A");
 preparedStatement.setString(3,"Ryan");
Lovely Professional University, Punjab
PreparedStatement
 The executeQuery() and executeUpdate()methods are similar to the ones defined in the
Statement interface except that they have no parameters, because the SQL statements are
already specified in the preparedStatement method when the object of PreparedStatement is
created.

Lovely Professional University, Punjab


Demo Programs
 SimpleJdbc.java(Demo Program)
 FindGrade1.java(Demo Program)
 FindGradeUsingPreparedStatements.java(Demo Program)

Lovely Professional University, Punjab


Retrieving Metadata
 JDBC provides the DatabaseMetaData interface for obtaining database
wide information and the ResultSetMetaData interface for obtaining
information on the specific ResultSet, such as column count and column
names.

Lovely Professional University, Punjab


Database Metadata
 The Connection interface establishes a connection to a database. It is
within the context of a connection that SQL statements are executed
and results are returned.

 A connection also provides access to database metadata information


that describes the capabilities of the database, supported SQL grammar,
stored procedures, and so on.

 To obtain an instance of Database- MetaData for a database, use the


getMetaData method on a connection object like this:
DatabaseMetaData dbMetaData = connection.getMetaData();
 TestDatabaseMetaData.java[Demo Program]
Lovely Professional University, Punjab
Result Set Metadata
 A ResultSetMetaData object can be used to find the types and properties
of the columns in a ResultSet. To obtain an instance of
ResultSetMetaData, use the getMetaData method on a result set like
this:
 ResultSetMetaData rsMetaData = resultSet.getMetaData();

 You can use the getColumnCount() method to find the number of


columns in the result and the getColumnName(int) method to get the
column names.

Lovely Professional University, Punjab


Result Set Metadata
 String getColumnName(int column)
Get the designated column's name
 int getColumnCount()
Returns the number of columns in this ResultSet object.
 boolean isReadOnly(int column)
Indicates whether the designated column is definitely not writable.
 boolean isSearchable(int column)
Indicates whether the designated column can be used in a where clause.
 String getTableName(int column)
Gets the designated column's table name.
 TestResultSetMetaData.java[Demo Program]

Lovely Professional University, Punjab


Batch Processing
 Statement = connection.createStatement();
// Add SQL commands to the batch
statement.addBatch("create table T (C1 integer, C2 varchar(15))");
statement.addBatch("insert into T values (100, 'Smith')");
statement.addBatch("insert into T values (200, 'Jones')");

// Execute the batch


int count[] = statement.executeBatch();
 NOTE:To find out whether a driver supports batch updates, invoke
supportsBatchUpdates() on a DatabaseMetaData instance.
 TestBatchProcessing.java[Demo Programs]

Lovely Professional University, Punjab


Why to setAutoCommit to false
 If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL
statement is committed to the database upon its completion.
 That may be fine for simple applications, but there are three reasons why you may want to turn
off auto-commit and manage your own transactions:
 To increase performance
 To maintain the integrity of business processes
 Transactions enable you to control if, and when, changes are applied to the database. It treats a
single SQL statement or a group of SQL statements as one logical unit, and if any statement
fails, the whole transaction fails.
 To enable manual- transaction support instead of the auto-commit mode that the JDBC driver
uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean
false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back
on again.
 For example, if you have a Connection object named conn, code the following to turn off auto-
commit:
conn.setAutoCommit(false);
Lovely Professional University, Punjab
Commit & Rollback
 try{
 //Assume a valid connection object conn
 conn.setAutoCommit(false);
 Statement stmt = conn.createStatement();
 String SQL = "INSERT INTO Employees " + "VALUES (106, 20, ‘Roshan', ‘Srivastava')";
 stmt.executeUpdate(SQL);
 //Submit a malformed SQL statement that breaks
 String SQL = "INSERTED IN Employees " + "VALUES (107, 22, 'Saurabh', 'Sharma')";
 stmt.executeUpdate(SQL);
 // If there is no error.
 conn.commit();
 }catch(SQLException se){
 // If there is any error.
 conn.rollback();
 }
Lovely Professional University, Punjab

Вам также может понравиться