SlideShare una empresa de Scribd logo
1 de 24
JDBC (Java Database Connectivity)
There are 4 different types of JDBC drivers: ,[object Object],[object Object],[object Object],[object Object],Important Classes: ,[object Object],[object Object],[object Object],[object Object],[object Object]
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 .
Loading the driver : Getting the connection from DriverManager : 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.  Class.forName( "DriverName" ); e.g.Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver" ); Connection connection = DriverManager.getConnection( "jdbc:microsoft:sqlserver://127.0.0.1ABCD:1443;”  + “ DatabaseName=JDBCDB" , "username" ,  "password" );
Sample *-ds.xml files for postgresql database : <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>
How to get Connection from the database? jndi.properties InitialContext initialContext =  new  InitialContext(); DataSource dataSource = (DataSource)   initialContext.lookup( &quot;PostgresDS&quot; ); Connection connection = dataSource.getConnection() java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=127.0.0.1:1099
2) Setting up Tables: Creating a Table: Creating JDBC Statements : executeQuery()   is used for select statements (DQL).   executeUpdate()   is used to create or modify tables (DDL and DML).   String createTableCoffees = &quot;CREATE TABLE COFFEES&quot; +  &quot; (COF_NAM VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT,&quot; +  &quot; SALES INTEGER, TOTAL INTEGER)&quot;;  Statement statement = connection.createStatement(); statement.executeUpdate(createTableCoffees);
Executing Statements : Entering Data into a Table : Getting Data from a Table : executeQuery( &quot;SELECT statement...&quot; )  executeUpdate( &quot;DDL and DML statements...&quot; )  Statement statement = connection.createStatement(); statement.executeUpdate(  &quot;INSERT INTO COFFEES &quot;  +  &quot;VALUES('Colombian', 101, 7.99, 0, 0&quot; );  ResultSet resultSet = statement.executeQuery( &quot;SELECT * FROM COFFEES&quot; );
3) Updating Tables: String query =  &quot;SELECT COF_NAME, SALES FROM COFFEES “  + &quot; WHERE COF_NAME LIKE 'Colombian'&quot; ; ResultSet resultSet = statement.executeQuery(query); while(rs.next()){ String s = resultSet.getString( &quot;COF_NAME&quot; );  int n = resultSet.getInt( &quot;SALES&quot; );  System.out.println(n +  &quot; ponds of &quot;  + s +  &quot; sold this week.&quot; ); } String updateString =  &quot;UPDATE COFFEES &quot;  +  &quot;SET TOTAL = TOTAL + 75 &quot;  +  &quot;WHERE COF_NAME LIKE 'Colombian'&quot; ; statement.executeUpdate(updateString);  String query =  &quot;SELECT COF_NAME, TOTAL FROM COFFEES&quot;  +  &quot;WHERE COF_NAME LIKE 'Colombian'&quot; ;  ResultSet resultSet = statment.executeQuery(query); while(rs.next()) {  String s = rs.getString(1);  int n = rs.getInt(2);  System.out.println(n +  &quot; ponds of &quot;  + s +  &quot; sold till date.&quot; );  }
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.
Creating a PreparedStatement Object: Supplying values for PreparedStatement Parameters: Code Fragment I: Code Fragment II: PreparedStatement updateSales = connection.preparedStatement( &quot;UPDATE COFFEES SET SALES = ? WHERE COF_NAME&quot; +  &quot; LIKE ? &quot; );   String updateString =  &quot;UPDATE COFFEES SET SALES=75 &quot;  +  &quot; WHERE COF_NAME LIKE 'Colombian'&quot; ; statement.executeUpdate(updateString);  PreparedStatement updateSales =  connection.preparedStatement(  &quot;UPDATE COFFEES SET SALES=? &quot;  +  &quot;WHERE COF_NAME LIKE ? &quot; ); updateSales.setInt(1, 75);  updateSales.setString(2,  &quot;Colombian&quot; ); updateSales.executeUpdate();
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.  Using a loop to set values: updateSales.setInt(1, 100); updateSales.setString(2,  &quot;French_Roast&quot; ); updateSales.executeUpdate(); updateSales.setString(2,  &quot;Espresso&quot; ); updateSales.executeUpdate();  PreparedStatement updateSales; String updateString =  &quot;update COFFEES &quot; +  &quot; set SALES = ? where COF_NAME like ?&quot; ; updateSales = con.preparedStatement(updateString); int [] salesForWeek = {175, 150, 60, 155, 90}; String [] coffees = ( &quot;Colombian&quot; ,  &quot;French_Roast&quot; ,  &quot;Colombian_Decaf&quot; ,  &quot;French_Roast_Decaf&quot; ); int len = coffees.length; for(int i=0; I < len; i++) {  updateSales.setInt(1, salesForWeek[i]); updateSales.setString(2, coffees[i]); updateSales.executeUpdate(); }
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.  When the method executeUpdate is used to execute a DDL statement, such as in creating a table, it returns the int 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.  updateSales.setInt(1, 50); updateSales.setString(2,  &quot;Espresso&quot; ); int  n = updateSales.executeUpdate(); // n = 1 because one row had a change in it. int  n = executeUpdate(createTableCoffees);  // n = 0
5) Using Joins: String createSUPPLIERS =  &quot;create table SUPPLIERS  &quot;  +  &quot;(SUP_ID INTEGER, SUP_NAME VARCHAR(40), &quot;  +  &quot;STREET VARCHAR(40), CITY VARCHAR(20), &quot;  + &quot;STATE CHAR(2), ZIP CHAR(5))&quot; ; statement.executeUpdate(createSUPPLIERS); statement.executeUpdate( &quot;insert int SUPPLIER values (101,  &quot;  + &quot;'Acme, Inc.', '99 Market Street', 'Groundsville', &quot;  + &quot;'CA', '95199'&quot; ); statement.executeUpdate( &quot;insert int SUPPLIERS values (49, &quot;  + &quot;'Superior Coffee', '1 Party Place', 'Mendocino', 'CA' &quot;   + &quot;'95460'&quot; ); statement.executeUpdate( &quot;Insert into SUPPLIERS value(150, &quot;  + &quot;'The High Ground', '100 Coffee Lane', 'Meadows', 'CA‘,  '93966'&quot; ; ResultSet rs = statement.executeQuery( &quot;select * from SUPPLIERS&quot; ); String query =  &quot;SELECT COFFEES.COF_NAME &quot;  + &quot;FROM COFFEES, SUPPLIERS &quot;  + &quot;WHERE SUPPLIERS.SUP_NAME LIKE 'Acme, Inc.' &quot;  + &quot;and SUPPLIER_ID = COFFEES.SUP_ID&quot; ; ResultSet rs = statement.executeQuery(query); System.out.println( &quot;Coffees bought from Acme, Inc.: &quot; ); while(rs.next()) { String coffeeName = rs.getString( &quot;COF_NAME&quot; );  System.out.println( &quot;  &quot;  + coffeeName); }
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 where connection is an active connection.  Committing a Transaction Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly.  connection.setAutoCommit( false );  connection.setAutoCommit( false ); PreparedStatement updateSales =  connection.preparedStatment(  &quot;UPDATE COFFEES SET TOTAL = TOTAL + &quot;  +  &quot; ? WHERE COF_NAME LIKE ?&quot; ); updateTotal.setInt(1, 50);  updateTotal.setString(2,  &quot;Colombian&quot; ); updateTotal.executeUpdate();  connection.commit();  connnection.setAutoCommit( true );
Using Transaction to Preserve Data Integrity Transaction isolation levels 1) 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; 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.  void  setTransactionIsolation( int  level)  throws   SQLException ;  int  getTransactionIsolation()  throws   SQLException ;
7) Using Stored Procedures: In SQL In Java (JDBC) Create procedure SHOW_SUPPLIERS As Select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME  from SUPPLIERS, COFFEES where SUPPLIERS.SUP_ID = COFFEES.SUP_ID Order by SUP_NAME 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);
Steps ,[object Object],[object Object],[object Object],[object Object],[object Object],8) Creating Complete JDBC Applications:
try  { - - - - - - }  catch  ( SQLException  ex) { System .err.println( “SQLException: ”  + ex.getMessage()); } try  { Class.forName( “myDriverClassName” ); }  catch  ( ClassNotFoundException  ex) { System .err.println( “ClassNotFoundException: ”  + ex.getMessage()); }
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( “ ” ); } }
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.
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(); } } ---
--- 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(); } } }
The End

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 
Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Php
PhpPhp
Php
 
React hooks
React hooksReact hooks
React hooks
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Android Networking
Android NetworkingAndroid Networking
Android Networking
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 

Destacado (20)

Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Scrum sprint structure workshop by Nermina Durmić
Scrum sprint structure workshop by Nermina DurmićScrum sprint structure workshop by Nermina Durmić
Scrum sprint structure workshop by Nermina Durmić
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Jsp
JspJsp
Jsp
 
Java Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP BasicJava Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP Basic
 
Ordbms
OrdbmsOrdbms
Ordbms
 
Software Quality Assurance
Software Quality AssuranceSoftware Quality Assurance
Software Quality Assurance
 
Verification and Validation in Software Engineering SE19
Verification and Validation in Software Engineering SE19Verification and Validation in Software Engineering SE19
Verification and Validation in Software Engineering SE19
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Black box & white-box testing technique
Black box & white-box testing techniqueBlack box & white-box testing technique
Black box & white-box testing technique
 

Similar a JDBC Java Database Connectivity

30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbcphanleson
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitPeter Wilcsinszky
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Databasejitendral
 
ADO.Net Improvements in .Net 2.0
ADO.Net Improvements in .Net 2.0ADO.Net Improvements in .Net 2.0
ADO.Net Improvements in .Net 2.0David Truxall
 
Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit TestingMike Lively
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.pptSwapnil Kale
 
Core Php Component Presentation
Core Php Component PresentationCore Php Component Presentation
Core Php Component PresentationJohn Coonen
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8PrinceGuru MS
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsphanleson
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 
Advanced dot net
Advanced dot netAdvanced dot net
Advanced dot netssa2010
 
My sql with querys
My sql with querysMy sql with querys
My sql with querysNIRMAL FELIX
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplicationolegmmiller
 

Similar a JDBC Java Database Connectivity (20)

30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
jdbc
jdbcjdbc
jdbc
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
ADO.Net Improvements in .Net 2.0
ADO.Net Improvements in .Net 2.0ADO.Net Improvements in .Net 2.0
ADO.Net Improvements in .Net 2.0
 
Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit Testing
 
Jsp And Jdbc
Jsp And JdbcJsp And Jdbc
Jsp And Jdbc
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
Core Php Component Presentation
Core Php Component PresentationCore Php Component Presentation
Core Php Component Presentation
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Jdbc
JdbcJdbc
Jdbc
 
Dat402
Dat402Dat402
Dat402
 
Advanced dot net
Advanced dot netAdvanced dot net
Advanced dot net
 
My java file
My java fileMy java file
My java file
 
WCF - In a Week
WCF - In a WeekWCF - In a Week
WCF - In a Week
 
My sql with querys
My sql with querysMy sql with querys
My sql with querys
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplication
 

Más de Ranjan Kumar

Introduction to java ee
Introduction to java eeIntroduction to java ee
Introduction to java eeRanjan Kumar
 
Fantastic life views ons
Fantastic life views  onsFantastic life views  ons
Fantastic life views onsRanjan Kumar
 
Story does not End here
Story does not End hereStory does not End here
Story does not End hereRanjan Kumar
 
Whata Split Second Looks Like
Whata Split Second Looks LikeWhata Split Second Looks Like
Whata Split Second Looks LikeRanjan Kumar
 
Friendship so Sweet
Friendship so SweetFriendship so Sweet
Friendship so SweetRanjan Kumar
 
Dear Son Dear Daughter
Dear Son Dear DaughterDear Son Dear Daughter
Dear Son Dear DaughterRanjan Kumar
 
Alaska Railway Routes
Alaska Railway RoutesAlaska Railway Routes
Alaska Railway RoutesRanjan Kumar
 
Poison that Kills the Dreams
Poison that Kills the DreamsPoison that Kills the Dreams
Poison that Kills the DreamsRanjan Kumar
 
Best Aviation Photography
Best Aviation PhotographyBest Aviation Photography
Best Aviation PhotographyRanjan Kumar
 

Más de Ranjan Kumar (20)

Introduction to java ee
Introduction to java eeIntroduction to java ee
Introduction to java ee
 
Fantastic life views ons
Fantastic life views  onsFantastic life views  ons
Fantastic life views ons
 
Lessons on Life
Lessons on LifeLessons on Life
Lessons on Life
 
Story does not End here
Story does not End hereStory does not End here
Story does not End here
 
Whata Split Second Looks Like
Whata Split Second Looks LikeWhata Split Second Looks Like
Whata Split Second Looks Like
 
Friendship so Sweet
Friendship so SweetFriendship so Sweet
Friendship so Sweet
 
Dedicate Time
Dedicate TimeDedicate Time
Dedicate Time
 
Paradise on Earth
Paradise on EarthParadise on Earth
Paradise on Earth
 
Bolivian Highway
Bolivian HighwayBolivian Highway
Bolivian Highway
 
Chinese Proverb
Chinese ProverbChinese Proverb
Chinese Proverb
 
Warren Buffet
Warren BuffetWarren Buffet
Warren Buffet
 
Dear Son Dear Daughter
Dear Son Dear DaughterDear Son Dear Daughter
Dear Son Dear Daughter
 
Jara Sochiye
Jara SochiyeJara Sochiye
Jara Sochiye
 
Blue Beauty
Blue BeautyBlue Beauty
Blue Beauty
 
Alaska Railway Routes
Alaska Railway RoutesAlaska Railway Routes
Alaska Railway Routes
 
Poison that Kills the Dreams
Poison that Kills the DreamsPoison that Kills the Dreams
Poison that Kills the Dreams
 
Horrible Jobs
Horrible JobsHorrible Jobs
Horrible Jobs
 
Best Aviation Photography
Best Aviation PhotographyBest Aviation Photography
Best Aviation Photography
 
Role of Attitude
Role of AttitudeRole of Attitude
Role of Attitude
 
45 Lesons in Life
45 Lesons in Life45 Lesons in Life
45 Lesons in Life
 

Último

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 

Último (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 

JDBC Java Database Connectivity

  • 1. JDBC (Java Database Connectivity)
  • 2.
  • 3. 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 .
  • 4. Loading the driver : Getting the connection from DriverManager : 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. Class.forName( &quot;DriverName&quot; ); e.g.Class.forName( &quot;com.microsoft.jdbc.sqlserver.SQLServerDriver&quot; ); Connection connection = DriverManager.getConnection( &quot;jdbc:microsoft:sqlserver://127.0.0.1ABCD:1443;” + “ DatabaseName=JDBCDB&quot; , &quot;username&quot; , &quot;password&quot; );
  • 5. Sample *-ds.xml files for postgresql database : <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>
  • 6. How to get Connection from the database? jndi.properties InitialContext initialContext = new InitialContext(); DataSource dataSource = (DataSource) initialContext.lookup( &quot;PostgresDS&quot; ); Connection connection = dataSource.getConnection() java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=127.0.0.1:1099
  • 7. 2) Setting up Tables: Creating a Table: Creating JDBC Statements : executeQuery() is used for select statements (DQL). executeUpdate() is used to create or modify tables (DDL and DML). String createTableCoffees = &quot;CREATE TABLE COFFEES&quot; + &quot; (COF_NAM VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT,&quot; + &quot; SALES INTEGER, TOTAL INTEGER)&quot;; Statement statement = connection.createStatement(); statement.executeUpdate(createTableCoffees);
  • 8. Executing Statements : Entering Data into a Table : Getting Data from a Table : executeQuery( &quot;SELECT statement...&quot; ) executeUpdate( &quot;DDL and DML statements...&quot; ) Statement statement = connection.createStatement(); statement.executeUpdate( &quot;INSERT INTO COFFEES &quot; + &quot;VALUES('Colombian', 101, 7.99, 0, 0&quot; ); ResultSet resultSet = statement.executeQuery( &quot;SELECT * FROM COFFEES&quot; );
  • 9. 3) Updating Tables: String query = &quot;SELECT COF_NAME, SALES FROM COFFEES “ + &quot; WHERE COF_NAME LIKE 'Colombian'&quot; ; ResultSet resultSet = statement.executeQuery(query); while(rs.next()){ String s = resultSet.getString( &quot;COF_NAME&quot; ); int n = resultSet.getInt( &quot;SALES&quot; ); System.out.println(n + &quot; ponds of &quot; + s + &quot; sold this week.&quot; ); } String updateString = &quot;UPDATE COFFEES &quot; + &quot;SET TOTAL = TOTAL + 75 &quot; + &quot;WHERE COF_NAME LIKE 'Colombian'&quot; ; statement.executeUpdate(updateString); String query = &quot;SELECT COF_NAME, TOTAL FROM COFFEES&quot; + &quot;WHERE COF_NAME LIKE 'Colombian'&quot; ; ResultSet resultSet = statment.executeQuery(query); while(rs.next()) { String s = rs.getString(1); int n = rs.getInt(2); System.out.println(n + &quot; ponds of &quot; + s + &quot; sold till date.&quot; ); }
  • 10. 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.
  • 11. Creating a PreparedStatement Object: Supplying values for PreparedStatement Parameters: Code Fragment I: Code Fragment II: PreparedStatement updateSales = connection.preparedStatement( &quot;UPDATE COFFEES SET SALES = ? WHERE COF_NAME&quot; + &quot; LIKE ? &quot; ); String updateString = &quot;UPDATE COFFEES SET SALES=75 &quot; + &quot; WHERE COF_NAME LIKE 'Colombian'&quot; ; statement.executeUpdate(updateString); PreparedStatement updateSales = connection.preparedStatement( &quot;UPDATE COFFEES SET SALES=? &quot; + &quot;WHERE COF_NAME LIKE ? &quot; ); updateSales.setInt(1, 75); updateSales.setString(2, &quot;Colombian&quot; ); updateSales.executeUpdate();
  • 12. 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. Using a loop to set values: updateSales.setInt(1, 100); updateSales.setString(2, &quot;French_Roast&quot; ); updateSales.executeUpdate(); updateSales.setString(2, &quot;Espresso&quot; ); updateSales.executeUpdate(); PreparedStatement updateSales; String updateString = &quot;update COFFEES &quot; + &quot; set SALES = ? where COF_NAME like ?&quot; ; updateSales = con.preparedStatement(updateString); int [] salesForWeek = {175, 150, 60, 155, 90}; String [] coffees = ( &quot;Colombian&quot; , &quot;French_Roast&quot; , &quot;Colombian_Decaf&quot; , &quot;French_Roast_Decaf&quot; ); int len = coffees.length; for(int i=0; I < len; i++) { updateSales.setInt(1, salesForWeek[i]); updateSales.setString(2, coffees[i]); updateSales.executeUpdate(); }
  • 13. 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. When the method executeUpdate is used to execute a DDL statement, such as in creating a table, it returns the int 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. updateSales.setInt(1, 50); updateSales.setString(2, &quot;Espresso&quot; ); int n = updateSales.executeUpdate(); // n = 1 because one row had a change in it. int n = executeUpdate(createTableCoffees); // n = 0
  • 14. 5) Using Joins: String createSUPPLIERS = &quot;create table SUPPLIERS &quot; + &quot;(SUP_ID INTEGER, SUP_NAME VARCHAR(40), &quot; + &quot;STREET VARCHAR(40), CITY VARCHAR(20), &quot; + &quot;STATE CHAR(2), ZIP CHAR(5))&quot; ; statement.executeUpdate(createSUPPLIERS); statement.executeUpdate( &quot;insert int SUPPLIER values (101, &quot; + &quot;'Acme, Inc.', '99 Market Street', 'Groundsville', &quot; + &quot;'CA', '95199'&quot; ); statement.executeUpdate( &quot;insert int SUPPLIERS values (49, &quot; + &quot;'Superior Coffee', '1 Party Place', 'Mendocino', 'CA' &quot; + &quot;'95460'&quot; ); statement.executeUpdate( &quot;Insert into SUPPLIERS value(150, &quot; + &quot;'The High Ground', '100 Coffee Lane', 'Meadows', 'CA‘, '93966'&quot; ; ResultSet rs = statement.executeQuery( &quot;select * from SUPPLIERS&quot; ); String query = &quot;SELECT COFFEES.COF_NAME &quot; + &quot;FROM COFFEES, SUPPLIERS &quot; + &quot;WHERE SUPPLIERS.SUP_NAME LIKE 'Acme, Inc.' &quot; + &quot;and SUPPLIER_ID = COFFEES.SUP_ID&quot; ; ResultSet rs = statement.executeQuery(query); System.out.println( &quot;Coffees bought from Acme, Inc.: &quot; ); while(rs.next()) { String coffeeName = rs.getString( &quot;COF_NAME&quot; ); System.out.println( &quot; &quot; + coffeeName); }
  • 15. 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 where connection is an active connection. Committing a Transaction Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly. connection.setAutoCommit( false ); connection.setAutoCommit( false ); PreparedStatement updateSales = connection.preparedStatment( &quot;UPDATE COFFEES SET TOTAL = TOTAL + &quot; + &quot; ? WHERE COF_NAME LIKE ?&quot; ); updateTotal.setInt(1, 50); updateTotal.setString(2, &quot;Colombian&quot; ); updateTotal.executeUpdate(); connection.commit(); connnection.setAutoCommit( true );
  • 16. Using Transaction to Preserve Data Integrity Transaction isolation levels 1) 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; 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. void setTransactionIsolation( int level) throws SQLException ; int getTransactionIsolation() throws SQLException ;
  • 17. 7) Using Stored Procedures: In SQL In Java (JDBC) Create procedure SHOW_SUPPLIERS As Select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME from SUPPLIERS, COFFEES where SUPPLIERS.SUP_ID = COFFEES.SUP_ID Order by SUP_NAME 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);
  • 18.
  • 19. try { - - - - - - } catch ( SQLException ex) { System .err.println( “SQLException: ” + ex.getMessage()); } try { Class.forName( “myDriverClassName” ); } catch ( ClassNotFoundException ex) { System .err.println( “ClassNotFoundException: ” + ex.getMessage()); }
  • 20. 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( “ ” ); } }
  • 21. 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.
  • 22. 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(); } } ---
  • 23. --- 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(); } } }