SlideShare ist ein Scribd-Unternehmen logo
1 von 23
Downloaden Sie, um offline zu lesen
PROGRAMMING IN JAVA
A. SIVASANKARI
ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER APPLICATION
SHANMUGA INDUSTRIES ARTS AND SCIENCE
COLLEGE,
TIRUVANNAMALAI. 606601.
Email: sivasankaridkm@gmail.com
PROGRAMMING IN JAVA
UNIT – 5
PART- II
 JDBC DRIVER AND ITS TYPES
 DATABASE URL FORMULATION
 CREATE CONNECTION OBJECT
 CLOSING JDBC CONNECTIONS
 DATA TYPES
 RESULT SETS
 CONCURRENCY OF RESULTSET
 VIEWING A RESULT SET
 TRANSACTIONS
 COMMIT & ROLLBACK
A. SIVASANKARI - SIASC-TVM UNIT-5
PROGRAMMING IN JAVA
JDBC - DRIVER AND ITS TYPES
DEFINITION OF JDBC DRIVER
• JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.
• For example, using JDBC drivers enable you to open database connections and to
interact with it by sending SQL or database commands then receiving results with Java.
• The Java.sql package that ships with JDK, contains various classes with their behaviours
defined and their actual implementaions are done in third-party drivers. Third party vendors
implements the java.sql.Driver interface in their database driver.
JDBC DRIVERS TYPES
• JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Such 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.
• When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when
no other alternative is available.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
• The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of
this kind of driver.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
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 are 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.
• If we change the Database, we have to change the native API, as it is specific to a
database and they are mostly obsolete now, but you may realize some speed increase
with a Type 2 driver, because it eliminates ODBC's overhead.
• The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
• Type 3: JDBC-Net pure Java
• In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients
use standard network sockets to communicate with a 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.
• This kind of driver is extremely flexible, since it requires no code installed on the client
and a single driver can actually provide access to multiple databases.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
Type 4: 100% Pure Java
• In a Type 4 driver, a pure Java-based driver communicates directly with the 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.
• MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
WHICH DRIVER SHOULD BE USED?
• If we are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.
• If our Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.
• Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.
• The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.
JDBC - DATABASE CONNECTIONS
• After you've installed the appropriate driver, it is time to establish a database connection using
JDBC.
• The programming involved to establish a JDBC connection is fairly simple. Here are these
simple four steps −
• Import JDBC Packages: Add import statements to your Java program to import required
classes in your Java code.
• Register JDBC Driver: This step causes the JVM to load the desired driver implementation
into memory so it can fulfill your JDBC requests.
• Database URL Formulation: This is to create a properly formatted address that points to the
database to which you wish to connect.
• Create Connection Object: Finally, code a call to
the DriverManager object's getConnection( ) method to establish actual database connection.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
DATABASE URL FORMULATION
• After you've loaded the driver, you can establish a connection using
the DriverManager.getConnection() method. For easy reference, let me list the three
overloaded DriverManager.getConnection() methods −
• getConnection(String url)
• getConnection(String url, Properties prop)
• getConnection(String url, String user, String password)
• Here each form requires a database URL. A database URL is an address that points to your
database.
• Formulating a database URL is where most of the problems associated with establishing a
connection occurs.
• Following table lists down the popular JDBC driver names and database URL.
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port Number:databaseName
DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port Number/databaseName
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
CREATE CONNECTION OBJECT
• We have listed down three forms of DriverManager.getConnection() method to create a
connection object.
• Using a Database URL with a username and password
• The most commonly used form of getConnection() requires you to pass a database URL,
a username, and a password:
• Assuming you are using Oracle's thin driver, you'll specify a host:port: databaseName value
for the database portion of the URL.
• If you have a host at TCP/IP address 192.0.0.1 with a host name of am rood, and your Oracle
listener is configured to listen on port 1521, and your database name is EMP, then complete
database URL would be −
• jdbc:oracle:thin:@amrood:1521:EMP
• Now you have to call getConnection() method with appropriate username and password to get
a Connection object as follows −
• String URL = "jdbc:oracle:thin:@amrood:1521:EMP";String USER = "username";String
PASS = "password"Connection conn = DriverManager.getConnection(URL, USER, PASS);
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
USING ONLY A DATABASE URL
• A second form of the DriverManager.getConnection( ) method requires only a database URL
• DriverManager.getConnection(String url);
• However, in this case, the database URL includes the username and password and has the
following general form −
• jdbc:oracle:driver:username/password@database
• So, the above connection can be created as follows −
• String URL = "jdbc:oracle:thin:username/password@amrood:1521:EMP";Connection conn =
DriverManager.getConnection(URL);
USING A DATABASE URLAND A PROPERTIES OBJECT
• A third form of the DriverManager.getConnection( ) method requires a database URL and a
Properties object −
• DriverManager.getConnection(String url, Properties info);
• A Properties object holds a set of keyword-value pairs. It is used to pass driver properties to
the driver during a call to the getConnection() method.
• To make the same connection made by the previous examples, use the following code −
• import java.util.*; String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
• Properties info = new Properties( );
• info.put( "user", "username" );
• info.put( "password", "password" );
• Connection conn = DriverManager.getConnection(URL, info);
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
CLOSING JDBC CONNECTIONS
• At the end of your JDBC program, it is required explicitly to close all the connections to
the database to end each database session. However, if you forget, Java's garbage
collector will close the connection when it cleans up stale objects.
• Relying on the garbage collection, especially in database programming, is a very poor
programming practice. You should make a habit of always closing the connection
with the close() method associated with connection object.
• To ensure that a connection is closed, you could provide a 'finally' block in your code.
A finally block always executes, regardless of an exception occurs or not.
• To close the above opened connection, you should call close() method as follows −
• conn.close();
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
JDBC - Statements, PreparedStatement and callableStatement
• Once a connection is obtained we can interact with the database. The JDBC Statement,
CallableStatement, and PreparedStatement interfaces define the methods and properties that
enable you to send SQL or PL/SQL commands and receive data from your database.
• They also define methods that help bridge data type differences between Java and SQL data
types used in a database.
• The following table provides a summary of each interface's purpose to decide on the interface
to use.Interfaces Recommended Use
Statement Use this for general-purpose access to your database. Useful when you
are using static SQL statements at runtime. The Statement interface
cannot accept parameters.
PreparedStatement Use this when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
CallableStatement Use this when you want to access the database stored procedures. The
CallableStatement interface can also accept runtime input parameters.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
JDBC - DATA TYPES
• The JDBC driver converts the Java data type to the appropriate JDBC type, before sending it
to the database. It uses a default mapping for most data types. For example, a Java int is
converted to an SQL INTEGER. Default mappings were created to provide consistency
between drivers.
• The following table summarizes the default JDBC data type that the Java data type is
converted to, when you call the setXXX() method of the PreparedStatement or
CallableStatement object or the ResultSet.updateXXX() method.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
SQL JDBC/Java setXXX updateXXX
VARCHAR java.lang.String setString updateString
CHAR java.lang.String setString updateString
LONGVARCHAR java.lang.String setString updateString
BIT boolean setBoolean updateBoolean
NUMERIC java.math.BigDecimal setBigDecimal updateBigDecimal
TINYINT byte setByte updateByte
SMALLINT short setShort updateShort
INTEGER int setInt updateInt
BIGINT long setLong updateLong
REAL float setFloat updateFloat
FLOAT float setFloat updateFloat
DOUBLE double setDouble updateDouble
VARBINARY byte[ ] setBytes updateBytes
BINARY byte[ ] setBytes updateBytes
DATE java.sql.Date setDate updateDate
TIME java.sql.Time setTime updateTime
TIMESTAMP java.sql.Timestamp setTimestamp updateTimestamp
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
JDBC - RESULT SETS
• The SQL statements that read data from a database query, return the data in a result
set. The SELECT statement is the standard way to select rows from a database
and view them in a result set. 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.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
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 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 generates
the ResultSet is created.
JDBC provides the 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 indicates 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.
.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
TYPES OF RESULTSET DESCRIPTION
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.
ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and backward, and
the result set is not sensitive to changes made by
others to the database that occur after the result set
was created.
ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward, and
the result set is sensitive to changes made by others
to the database that occur after the result set was
created.
A. SIVASANKARI - SIASC-TVM
TYPE OF RESULTSET
The possible RSType are given below. If you do not specify any ResultSet type, you
will automatically get one that is TYPE_FORWARD_ONLY.
PROGRAMMING IN JAVA
CONCURRENCY OF RESULTSET
• The possible RSConcurrency are given below. If you do not specify any Concurrency type,
you will automatically get one that is CONCUR_READ_ONLY.
• All our examples written so far can be written as follows, which initializes a Statement object
to create a forward-only, read only ResultSet object −
• try {
• Statement stmt = conn.createStatement( ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);}
• catch(Exception ex)
• { ....}
• finally
• { ....}
CONCURRENCY DESCRIPTION
ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the default
ResultSet.CONCUR_UPDATABLE Creates an updateable result set.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
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.
S.N. METHODS & DESCRIPTION
1 public int getInt(String columnName) throws SQLException
Returns the int in the current row in the column named columnName.
2 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.
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
JDBC - TRANSACTIONS
• If our 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 the auto-commit and manage your own transactions −
• To increase performance.
• To maintain the integrity of business processes.
• To use distributed transactions.
• 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);
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVACOMMIT & ROLLBACK
Once you are done with your changes and you want to commit the changes then
call commit() method on connection object as follows
• conn.commit( );
Otherwise, to roll back updates to the database made using the Connection named conn, use the
following code −
• conn.rollback( );
The following example illustrates the use of a commit and rollback object −
• try{ //Assume a valid connection object
• conn conn.setAutoCommit(false);
• Statement stmt = conn.createStatement();
• String SQL = "INSERT INTO Employees " +
• "VALUES (106, 20, 'Rajesh', ‘Babu')";
• stmt.executeUpdate(SQL);
• //Submit a malformed SQL statement that breaks
• String SQL = "INSERTED IN Employees " +
• "VALUES (107, 22, 'Sobia', 'Suresh')";
• stmt.executeUpdate(SQL); // If there is no error.
• conn.commit();}
• catch(SQLException se){ // If there is any error.
• conn.rollback();
• }
A. SIVASANKARI - SIASC-TVM
A. SIVASANKARI - SIASC-TVM

Weitere ähnliche Inhalte

Was ist angesagt?

2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc driversmyrajendra
 
Advanced java
Advanced java Advanced java
Advanced java NA
 
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010Arun Gupta
 
Moving complex enterprise ecommerce systems to the cloud
Moving complex enterprise ecommerce systems to the cloudMoving complex enterprise ecommerce systems to the cloud
Moving complex enterprise ecommerce systems to the cloudElastic Path
 
JAVA BOOK BY SIVASANKARI
JAVA BOOK BY SIVASANKARIJAVA BOOK BY SIVASANKARI
JAVA BOOK BY SIVASANKARISivaSankari36
 
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBCBI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBCSimba Technologies
 
Advance java Online Training in Hyderabad
Advance java Online Training in HyderabadAdvance java Online Training in Hyderabad
Advance java Online Training in HyderabadUgs8008
 
Turbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk ProcessingTurbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk ProcessingSteven Feuerstein
 

Was ist angesagt? (20)

Advanced JAVA
Advanced JAVAAdvanced JAVA
Advanced JAVA
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
Advanced java
Advanced java Advanced java
Advanced java
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Css
CssCss
Css
 
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
 
Moving complex enterprise ecommerce systems to the cloud
Moving complex enterprise ecommerce systems to the cloudMoving complex enterprise ecommerce systems to the cloud
Moving complex enterprise ecommerce systems to the cloud
 
JAVA BOOK BY SIVASANKARI
JAVA BOOK BY SIVASANKARIJAVA BOOK BY SIVASANKARI
JAVA BOOK BY SIVASANKARI
 
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBCBI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
 
Dao example
Dao exampleDao example
Dao example
 
Getting started with laravel
Getting started with laravelGetting started with laravel
Getting started with laravel
 
Advance Java
Advance JavaAdvance Java
Advance Java
 
Advance java Online Training in Hyderabad
Advance java Online Training in HyderabadAdvance java Online Training in Hyderabad
Advance java Online Training in Hyderabad
 
Turbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk ProcessingTurbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk Processing
 
What Is Hobo ?
What Is Hobo ?What Is Hobo ?
What Is Hobo ?
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
Jdbc basic features
Jdbc basic featuresJdbc basic features
Jdbc basic features
 
Java1
Java1Java1
Java1
 
Java1
Java1Java1
Java1
 

Ähnlich wie PROGRAMMING IN JAVA- unit 5-part II

java database connectivity for java programming
java database connectivity for java programmingjava database connectivity for java programming
java database connectivity for java programmingrinky1234
 
java.pptx
java.pptxjava.pptx
java.pptxbfgd1
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5Pallepati Vasavi
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...Pallepati Vasavi
 
OOP Lecture 17-DB Connectivity-Part1.pptx
OOP Lecture 17-DB Connectivity-Part1.pptxOOP Lecture 17-DB Connectivity-Part1.pptx
OOP Lecture 17-DB Connectivity-Part1.pptxTanzila Kehkashan
 
Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2msafad
 
chapter 5 java.pptx
chapter 5  java.pptxchapter 5  java.pptx
chapter 5 java.pptxBekiTube
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)suraj pandey
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.pptNaveenKumar648465
 
java database connection (jdbc)
java database connection (jdbc)java database connection (jdbc)
java database connection (jdbc)Sanjay Gunjal
 

Ähnlich wie PROGRAMMING IN JAVA- unit 5-part II (20)

java database connectivity for java programming
java database connectivity for java programmingjava database connectivity for java programming
java database connectivity for java programming
 
java.pptx
java.pptxjava.pptx
java.pptx
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
jdbc
jdbcjdbc
jdbc
 
Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
 
JDBC
JDBCJDBC
JDBC
 
OOP Lecture 17-DB Connectivity-Part1.pptx
OOP Lecture 17-DB Connectivity-Part1.pptxOOP Lecture 17-DB Connectivity-Part1.pptx
OOP Lecture 17-DB Connectivity-Part1.pptx
 
Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2
 
Jdbc
JdbcJdbc
Jdbc
 
chapter 5 java.pptx
chapter 5  java.pptxchapter 5  java.pptx
chapter 5 java.pptx
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)
 
Jdbc
JdbcJdbc
Jdbc
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
java database connection (jdbc)
java database connection (jdbc)java database connection (jdbc)
java database connection (jdbc)
 
java 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptxjava 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptx
 
Jdbc
JdbcJdbc
Jdbc
 

Mehr von SivaSankari36

DATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARIDATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARISivaSankari36
 
CLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARICLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARISivaSankari36
 
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARIMOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARISivaSankari36
 
MOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARIMOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARISivaSankari36
 
Functional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data ApplicationFunctional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data ApplicationSivaSankari36
 
Java unit1 b- Java Operators to Methods
Java  unit1 b- Java Operators to MethodsJava  unit1 b- Java Operators to Methods
Java unit1 b- Java Operators to MethodsSivaSankari36
 

Mehr von SivaSankari36 (6)

DATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARIDATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARI
 
CLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARICLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARI
 
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARIMOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
 
MOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARIMOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARI
 
Functional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data ApplicationFunctional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data Application
 
Java unit1 b- Java Operators to Methods
Java  unit1 b- Java Operators to MethodsJava  unit1 b- Java Operators to Methods
Java unit1 b- Java Operators to Methods
 

Kürzlich hochgeladen

CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapitolTechU
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfMohonDas
 
Philosophy of Education and Educational Philosophy
Philosophy of Education  and Educational PhilosophyPhilosophy of Education  and Educational Philosophy
Philosophy of Education and Educational PhilosophyShuvankar Madhu
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxDr. Santhosh Kumar. N
 
Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.EnglishCEIPdeSigeiro
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17Celine George
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxKatherine Villaluna
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17Celine George
 
3.21.24 The Origins of Black Power.pptx
3.21.24  The Origins of Black Power.pptx3.21.24  The Origins of Black Power.pptx
3.21.24 The Origins of Black Power.pptxmary850239
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptxSandy Millin
 
General views of Histopathology and step
General views of Histopathology and stepGeneral views of Histopathology and step
General views of Histopathology and stepobaje godwin sunday
 
How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17Celine George
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice documentXsasf Sfdfasd
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfTechSoup
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxSaurabhParmar42
 
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxPISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxEduSkills OECD
 
How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17Celine George
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxiammrhaywood
 

Kürzlich hochgeladen (20)

Prelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quizPrelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quiz
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptx
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdf
 
Philosophy of Education and Educational Philosophy
Philosophy of Education  and Educational PhilosophyPhilosophy of Education  and Educational Philosophy
Philosophy of Education and Educational Philosophy
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptx
 
Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptx
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17
 
3.21.24 The Origins of Black Power.pptx
3.21.24  The Origins of Black Power.pptx3.21.24  The Origins of Black Power.pptx
3.21.24 The Origins of Black Power.pptx
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
 
General views of Histopathology and step
General views of Histopathology and stepGeneral views of Histopathology and step
General views of Histopathology and step
 
How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice document
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptx
 
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxPISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
 
Personal Resilience in Project Management 2 - TV Edit 1a.pdf
Personal Resilience in Project Management 2 - TV Edit 1a.pdfPersonal Resilience in Project Management 2 - TV Edit 1a.pdf
Personal Resilience in Project Management 2 - TV Edit 1a.pdf
 
How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
 

PROGRAMMING IN JAVA- unit 5-part II

  • 1. PROGRAMMING IN JAVA A. SIVASANKARI ASSISTANT PROFESSOR DEPARTMENT OF COMPUTER APPLICATION SHANMUGA INDUSTRIES ARTS AND SCIENCE COLLEGE, TIRUVANNAMALAI. 606601. Email: sivasankaridkm@gmail.com
  • 2. PROGRAMMING IN JAVA UNIT – 5 PART- II  JDBC DRIVER AND ITS TYPES  DATABASE URL FORMULATION  CREATE CONNECTION OBJECT  CLOSING JDBC CONNECTIONS  DATA TYPES  RESULT SETS  CONCURRENCY OF RESULTSET  VIEWING A RESULT SET  TRANSACTIONS  COMMIT & ROLLBACK A. SIVASANKARI - SIASC-TVM UNIT-5
  • 3. PROGRAMMING IN JAVA JDBC - DRIVER AND ITS TYPES DEFINITION OF JDBC DRIVER • JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your database server. • For example, using JDBC drivers enable you to open database connections and to interact with it by sending SQL or database commands then receiving results with Java. • The Java.sql package that ships with JDK, contains various classes with their behaviours defined and their actual implementaions are done in third-party drivers. Third party vendors implements the java.sql.Driver interface in their database driver. JDBC DRIVERS TYPES • JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Such 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. • When Java first came out, this was a useful driver because most databases only supported ODBC access but now this type of driver is recommended only for experimental use or when no other alternative is available. A. SIVASANKARI - SIASC-TVM
  • 4. PROGRAMMING IN JAVA • The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver. A. SIVASANKARI - SIASC-TVM
  • 5. PROGRAMMING IN JAVA 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 are 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. • If we change the Database, we have to change the native API, as it is specific to a database and they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's overhead. • The Oracle Call Interface (OCI) driver is an example of a Type 2 driver. A. SIVASANKARI - SIASC-TVM
  • 6. PROGRAMMING IN JAVA • Type 3: JDBC-Net pure Java • In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use standard network sockets to communicate with a 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. • This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can actually provide access to multiple databases. A. SIVASANKARI - SIASC-TVM
  • 7. PROGRAMMING IN JAVA Type 4: 100% Pure Java • In a Type 4 driver, a pure Java-based driver communicates directly with the 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. • MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers. A. SIVASANKARI - SIASC-TVM
  • 8. PROGRAMMING IN JAVA WHICH DRIVER SHOULD BE USED? • If we are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4. • If our Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver. • Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for your database. • The type 1 driver is not considered a deployment-level driver, and is typically used for development and testing purposes only. JDBC - DATABASE CONNECTIONS • After you've installed the appropriate driver, it is time to establish a database connection using JDBC. • The programming involved to establish a JDBC connection is fairly simple. Here are these simple four steps − • Import JDBC Packages: Add import statements to your Java program to import required classes in your Java code. • Register JDBC Driver: This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests. • Database URL Formulation: This is to create a properly formatted address that points to the database to which you wish to connect. • Create Connection Object: Finally, code a call to the DriverManager object's getConnection( ) method to establish actual database connection. A. SIVASANKARI - SIASC-TVM
  • 9. PROGRAMMING IN JAVA DATABASE URL FORMULATION • After you've loaded the driver, you can establish a connection using the DriverManager.getConnection() method. For easy reference, let me list the three overloaded DriverManager.getConnection() methods − • getConnection(String url) • getConnection(String url, Properties prop) • getConnection(String url, String user, String password) • Here each form requires a database URL. A database URL is an address that points to your database. • Formulating a database URL is where most of the problems associated with establishing a connection occurs. • Following table lists down the popular JDBC driver names and database URL. RDBMS JDBC driver name URL format MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port Number:databaseName DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port Number/databaseName A. SIVASANKARI - SIASC-TVM
  • 10. PROGRAMMING IN JAVA CREATE CONNECTION OBJECT • We have listed down three forms of DriverManager.getConnection() method to create a connection object. • Using a Database URL with a username and password • The most commonly used form of getConnection() requires you to pass a database URL, a username, and a password: • Assuming you are using Oracle's thin driver, you'll specify a host:port: databaseName value for the database portion of the URL. • If you have a host at TCP/IP address 192.0.0.1 with a host name of am rood, and your Oracle listener is configured to listen on port 1521, and your database name is EMP, then complete database URL would be − • jdbc:oracle:thin:@amrood:1521:EMP • Now you have to call getConnection() method with appropriate username and password to get a Connection object as follows − • String URL = "jdbc:oracle:thin:@amrood:1521:EMP";String USER = "username";String PASS = "password"Connection conn = DriverManager.getConnection(URL, USER, PASS); A. SIVASANKARI - SIASC-TVM
  • 11. PROGRAMMING IN JAVA USING ONLY A DATABASE URL • A second form of the DriverManager.getConnection( ) method requires only a database URL • DriverManager.getConnection(String url); • However, in this case, the database URL includes the username and password and has the following general form − • jdbc:oracle:driver:username/password@database • So, the above connection can be created as follows − • String URL = "jdbc:oracle:thin:username/password@amrood:1521:EMP";Connection conn = DriverManager.getConnection(URL); USING A DATABASE URLAND A PROPERTIES OBJECT • A third form of the DriverManager.getConnection( ) method requires a database URL and a Properties object − • DriverManager.getConnection(String url, Properties info); • A Properties object holds a set of keyword-value pairs. It is used to pass driver properties to the driver during a call to the getConnection() method. • To make the same connection made by the previous examples, use the following code − • import java.util.*; String URL = "jdbc:oracle:thin:@amrood:1521:EMP"; • Properties info = new Properties( ); • info.put( "user", "username" ); • info.put( "password", "password" ); • Connection conn = DriverManager.getConnection(URL, info); A. SIVASANKARI - SIASC-TVM
  • 12. PROGRAMMING IN JAVA CLOSING JDBC CONNECTIONS • At the end of your JDBC program, it is required explicitly to close all the connections to the database to end each database session. However, if you forget, Java's garbage collector will close the connection when it cleans up stale objects. • Relying on the garbage collection, especially in database programming, is a very poor programming practice. You should make a habit of always closing the connection with the close() method associated with connection object. • To ensure that a connection is closed, you could provide a 'finally' block in your code. A finally block always executes, regardless of an exception occurs or not. • To close the above opened connection, you should call close() method as follows − • conn.close(); A. SIVASANKARI - SIASC-TVM
  • 13. PROGRAMMING IN JAVA JDBC - Statements, PreparedStatement and callableStatement • Once a connection is obtained we can interact with the database. The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your database. • They also define methods that help bridge data type differences between Java and SQL data types used in a database. • The following table provides a summary of each interface's purpose to decide on the interface to use.Interfaces Recommended Use Statement Use this for general-purpose access to your database. Useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters. PreparedStatement Use this when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime. CallableStatement Use this when you want to access the database stored procedures. The CallableStatement interface can also accept runtime input parameters. A. SIVASANKARI - SIASC-TVM
  • 14. PROGRAMMING IN JAVA JDBC - DATA TYPES • The JDBC driver converts the Java data type to the appropriate JDBC type, before sending it to the database. It uses a default mapping for most data types. For example, a Java int is converted to an SQL INTEGER. Default mappings were created to provide consistency between drivers. • The following table summarizes the default JDBC data type that the Java data type is converted to, when you call the setXXX() method of the PreparedStatement or CallableStatement object or the ResultSet.updateXXX() method. A. SIVASANKARI - SIASC-TVM
  • 15. PROGRAMMING IN JAVA SQL JDBC/Java setXXX updateXXX VARCHAR java.lang.String setString updateString CHAR java.lang.String setString updateString LONGVARCHAR java.lang.String setString updateString BIT boolean setBoolean updateBoolean NUMERIC java.math.BigDecimal setBigDecimal updateBigDecimal TINYINT byte setByte updateByte SMALLINT short setShort updateShort INTEGER int setInt updateInt BIGINT long setLong updateLong REAL float setFloat updateFloat FLOAT float setFloat updateFloat DOUBLE double setDouble updateDouble VARBINARY byte[ ] setBytes updateBytes BINARY byte[ ] setBytes updateBytes DATE java.sql.Date setDate updateDate TIME java.sql.Time setTime updateTime TIMESTAMP java.sql.Timestamp setTimestamp updateTimestamp A. SIVASANKARI - SIASC-TVM
  • 16. PROGRAMMING IN JAVA JDBC - RESULT SETS • The SQL statements that read data from a database query, return the data in a result set. The SELECT statement is the standard way to select rows from a database and view them in a result set. 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. A. SIVASANKARI - SIASC-TVM
  • 17. PROGRAMMING IN JAVA 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 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 generates the ResultSet is created. JDBC provides the 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 indicates 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. . A. SIVASANKARI - SIASC-TVM
  • 18. PROGRAMMING IN JAVA TYPES OF RESULTSET DESCRIPTION ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set. ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and backward, and the result set is not sensitive to changes made by others to the database that occur after the result set was created. ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward, and the result set is sensitive to changes made by others to the database that occur after the result set was created. A. SIVASANKARI - SIASC-TVM TYPE OF RESULTSET The possible RSType are given below. If you do not specify any ResultSet type, you will automatically get one that is TYPE_FORWARD_ONLY.
  • 19. PROGRAMMING IN JAVA CONCURRENCY OF RESULTSET • The possible RSConcurrency are given below. If you do not specify any Concurrency type, you will automatically get one that is CONCUR_READ_ONLY. • All our examples written so far can be written as follows, which initializes a Statement object to create a forward-only, read only ResultSet object − • try { • Statement stmt = conn.createStatement( ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);} • catch(Exception ex) • { ....} • finally • { ....} CONCURRENCY DESCRIPTION ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the default ResultSet.CONCUR_UPDATABLE Creates an updateable result set. A. SIVASANKARI - SIASC-TVM
  • 20. PROGRAMMING IN JAVA 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. S.N. METHODS & DESCRIPTION 1 public int getInt(String columnName) throws SQLException Returns the int in the current row in the column named columnName. 2 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. A. SIVASANKARI - SIASC-TVM
  • 21. PROGRAMMING IN JAVA JDBC - TRANSACTIONS • If our 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 the auto-commit and manage your own transactions − • To increase performance. • To maintain the integrity of business processes. • To use distributed transactions. • 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); A. SIVASANKARI - SIASC-TVM
  • 22. PROGRAMMING IN JAVACOMMIT & ROLLBACK Once you are done with your changes and you want to commit the changes then call commit() method on connection object as follows • conn.commit( ); Otherwise, to roll back updates to the database made using the Connection named conn, use the following code − • conn.rollback( ); The following example illustrates the use of a commit and rollback object − • try{ //Assume a valid connection object • conn conn.setAutoCommit(false); • Statement stmt = conn.createStatement(); • String SQL = "INSERT INTO Employees " + • "VALUES (106, 20, 'Rajesh', ‘Babu')"; • stmt.executeUpdate(SQL); • //Submit a malformed SQL statement that breaks • String SQL = "INSERTED IN Employees " + • "VALUES (107, 22, 'Sobia', 'Suresh')"; • stmt.executeUpdate(SQL); // If there is no error. • conn.commit();} • catch(SQLException se){ // If there is any error. • conn.rollback(); • } A. SIVASANKARI - SIASC-TVM
  • 23. A. SIVASANKARI - SIASC-TVM