SlideShare a Scribd company logo
JSP&DB Programming By:  Mr. PHUPHA PUNYAPOTASAKUL ( ภูผา ปัญญาโพธาสกุล )
Architecture
JDBC Connect to a data source, like a database  Send queries and update statements to the database  Retrieve and process the results received from the database in answer to your query
Establish connection Initialize driver Class . forName ( driver ) ; Create Connection Connection conn = DriverManager . getConnection ( url,user,password ) ; Each JDBC Vendor may use different driver class name and url
Driver class name and URL example Oracle 10i driver = oracle . jdbc . driver . OracleDriver url = jdbc : oracle : thin : @ // {DBSERVER} : 1521 / {DBNAME} MySQL 4 . x, 5 . x driver = com . mysql . jdbc . Driver url = jdbc : mysql :// {DBSERVER} / {DBNAME} MS SQLServer 2000, 2005 driver = com . microsoft . sqlserver . jdbc . SQLServerDriver url = jdbc : sqlserver :// {DBSERVER} : 1433;databaseName = {DBNAME};integratedSecurity = false;
Create statement and execute SQL command Create statement Statement stmt  = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY ) ; Execute Update stmt.execut eUpdate ( sql );   Execute Query ResultSet rs  =  stmt . executeQuery ( sql ) ;
ResultSet type TYPE_FORWARD_ONLY  — The result set is not scrollable; its cursor moves forward only, from before the first row to after the last row. The rows contained in the result set depend on how the underlying database materializes the results. That is, it contains the rows that satisfy the query at either the time the query is executed or as the rows are retrieved.  TYPE_SCROLL_INSENSITIVE  — The result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position .  TYPE_SCROLL_SENSITIVE  — The result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position.
Concurent Type CONCUR_READ_ONLY CONCUR_UPDATABLE
ResultSet movement next ()  - moves the cursor forward one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned after the last row.  previous ()  - moves the cursor backwards one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned before the first row.  first ()  - moves the cursor to the first row in the  ResultSet  object. Returns true if the cursor is now positioned on the first row and false if the  ResultSet  object does not contain any rows.  last()  -  moves the cursor to the last row in the  ResultSet  object .  Returns true if the cursor is now positioned on the last row and false if the  ResultSet  object does not contain any rows .
ResultSet movement beforeFirst()  -  positions the cursor at the start of the  ResultSet  object, before the first row .  If the  ResultSet  object does not contain any rows, this method has no effect .  afterLast()  -  positions the cursor at the end of the  ResultSet  object, after the last row .  If the  ResultSet  object does not contain any rows, this method has no effect .  relative(int rows)  -  moves the cursor relative to its current position .  absolute(int row)  -  positions the cursor on the row - th row of the  ResultSet  object .
Retrieving data Data type conversion getString() getInt() getFloat() getDate() etc. 2 ways to retrieve data e.g. select product_name from product By column name getString("product_name"); By column index (start from 1) getString(1);
Updating data Only if using CONCUR_UPDATABLE Not all JDBC Driver support this mode Data type conversion upateString() updateInt() updateFloat() updateDate() etc. Be able to use both column name and index
Updating data To insert a new record rs.moveToInsertRow() rs.updateString(1,"XXX"); rs.insertRow(); To update a record //move to expected record rs.updateString(1,"XXX"); rs.updateRow(); To delete a record //move to expected record rs.deleteRow();
Exception handling Connection conn = null; Statement stmt = null; ResultSet rs = null; try{ ... }catch ( SQLException ex ) { String sqlErr ="" ; while  ( ex  !=  null )  { sqlErr = sqlErr  + " \nMessage :  " +  ex . getMessage () ; sqlErr = sqlErr  + " \nSQLState :  " +  ex . getSQLState () ; sqlErr = sqlErr  + " \nErrorCode : " +  ex . getErrorCode () ; sqlErr = sqlErr  + " \n -----------------------------------------------------------" ; ex  =  ex . getNextException () ; } System . out . println ( sqlErr ) ; }catch ( Exception ex ) { ex . printStackTrace () ; }finally{ try{ if ( rs != null )  rs . close () ; }catch ( Exception e ) {} try{ if ( stmt != null )  stmt . close () ; }catch ( Exception e ) {} try{ if ( conn != null )  conn . close () ; }catch ( Exception e ) {} }
Prepared Statement Create Statement PreparedStatement pstmt  =  conn . prepareStatement ( sql,rtype,concur ) ; SQL with parameter using "?" E.g. select * from product where product_id=? and is_enable=? Set parameter value setString() setFloat() setInt() setDate()
Prepared Statement Use parameter index only - can't use column name (start from 1) pstmt.setString(1,"XXX"); Execute query or update normally ResultSet rs=pstmt.executeQuery(); pstmt.executeUpdate(); Re-usable
Question & Answer

More Related Content

What's hot (19)

PDF
[1062BPY12001] Data analysis with R / April 26
Kevin Chun-Hsien Hsu
 
DOCX
Function
Durgaprasad Yadav
 
PPTX
Mysql creating stored function
Prof.Nilesh Magar
 
PDF
Queue as data_structure
eShikshak
 
PPTX
Getting functional with elixir
Athira Mukundan
 
PPTX
Procedures and triggers in SQL
Vikash Sharma
 
PPT
Queue
Nabeel Ahsen
 
PDF
Apache Pig Relational Operators - II
Rupak Roy
 
PPTX
Insertion sort algorithm power point presentation
University of Science and Technology Chitttagong
 
PDF
Python my sql database connection
Learnbay Datascience
 
PPT
MySQL Views
Reggie Niccolo Santos
 
PPTX
Chapter 3 stored procedures
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Extracting a Micro State Transition Table Using KLEE
Norihiro Yoshida
 
PPTX
Clase 13 integridad modificada
Titiushko Jazz
 
PPT
Oracle Database Trigger
Eryk Budi Pratama
 
PPTX
Queue
Bhavesh Parmar
 
DOCX
Connectivity coding for java and mysql
Fahad Ali Khan
 
[1062BPY12001] Data analysis with R / April 26
Kevin Chun-Hsien Hsu
 
Mysql creating stored function
Prof.Nilesh Magar
 
Queue as data_structure
eShikshak
 
Getting functional with elixir
Athira Mukundan
 
Procedures and triggers in SQL
Vikash Sharma
 
Apache Pig Relational Operators - II
Rupak Roy
 
Insertion sort algorithm power point presentation
University of Science and Technology Chitttagong
 
Python my sql database connection
Learnbay Datascience
 
Extracting a Micro State Transition Table Using KLEE
Norihiro Yoshida
 
Clase 13 integridad modificada
Titiushko Jazz
 
Oracle Database Trigger
Eryk Budi Pratama
 
Connectivity coding for java and mysql
Fahad Ali Khan
 

Viewers also liked (20)

PPS
Abzolute Logistic Solution
phuphax
 
PDF
Weather patterns
Highline Academy
 
PPT
Jdbc (database in java)
Maher Abdo
 
PPTX
Java.sql package
myrajendra
 
PPT
JDBC
Ankit Desai
 
PPT
JDBC Tutorial
Information Technology
 
PPTX
Kansainvälisyysstrategia 2.0 ja OPS-2016
Tiina Sarisalmi
 
PDF
Interesting Sights in Orivesi
Tiina Sarisalmi
 
PPT
Cineas Corso Taylor Made Per Zurich 28 Aprile 2010 Ramo Malattia
Marco Contini
 
PDF
Everyday Life Questionnaire Results 2009
Tiina Sarisalmi
 
PDF
Green building
ANM Farukh
 
PDF
Will Rogers IAAP May Mtg Invitation
cbradley
 
PDF
Can Taltavuit Ibiza. Magnificient Villa for Vacation Rentals in Ibiza
Javier Pérez Gallego ★★★★★ The DOER Ibiza
 
PPTX
Regina drury firepole marketing presentation
Regina Drury
 
PDF
Iside 26 05e Frodi Assicurazioni
Marco Contini
 
PDF
Boardwalk Capital overview
Scott Sadler
 
PDF
A protest in respect to my sir
ANM Farukh
 
PPT
Finnish baseball
Tiina Sarisalmi
 
PPT
Polish Cuisine Book
Tiina Sarisalmi
 
Abzolute Logistic Solution
phuphax
 
Weather patterns
Highline Academy
 
Jdbc (database in java)
Maher Abdo
 
Java.sql package
myrajendra
 
JDBC Tutorial
Information Technology
 
Kansainvälisyysstrategia 2.0 ja OPS-2016
Tiina Sarisalmi
 
Interesting Sights in Orivesi
Tiina Sarisalmi
 
Cineas Corso Taylor Made Per Zurich 28 Aprile 2010 Ramo Malattia
Marco Contini
 
Everyday Life Questionnaire Results 2009
Tiina Sarisalmi
 
Green building
ANM Farukh
 
Will Rogers IAAP May Mtg Invitation
cbradley
 
Can Taltavuit Ibiza. Magnificient Villa for Vacation Rentals in Ibiza
Javier Pérez Gallego ★★★★★ The DOER Ibiza
 
Regina drury firepole marketing presentation
Regina Drury
 
Iside 26 05e Frodi Assicurazioni
Marco Contini
 
Boardwalk Capital overview
Scott Sadler
 
A protest in respect to my sir
ANM Farukh
 
Finnish baseball
Tiina Sarisalmi
 
Polish Cuisine Book
Tiina Sarisalmi
 
Ad

Similar to KMUTNB - Internet Programming 6/7 (20)

PPT
Scrollable Updatable
leminhvuong
 
PPT
Scrollable Updatable
phanleson
 
PPT
Executing Sql Commands
leminhvuong
 
PPT
Executing Sql Commands
phanleson
 
PPT
30 5 Database Jdbc
phanleson
 
PPT
JDBC – Java Database Connectivity
Information Technology
 
PPT
4. Database Connectivity using JDBC .ppt
HITENKHEMANI
 
PDF
java4th.pdf bilgisayar mühendisliği bölümü
Smeyyeztrk10
 
PPT
Jdbc
smvdurajesh
 
PPT
JDBC for CSQL Database
jitendral
 
PPTX
Discuss the scrollable result set in jdbc
manojmanoj218596
 
PPT
Jdbc oracle
yazidds2
 
PPT
JDBC.ppt JDBC_FM_2012_201JDBC_FM_2012_201
rorebik626
 
PPT
JDBC_Template for database connection using Spring
gangishettysaikrishn
 
PDF
Jdbc[1]
Fulvio Corno
 
PDF
JDBC programming
Fulvio Corno
 
PPT
jdbc
vikram singh
 
PDF
Java 1-contd
Mukesh Tekwani
 
PPT
JDBC (2).ppt
manvibaunthiyal1
 
PPTX
Java Databse Connectvity- Alex Jose
Dipayan Sarkar
 
Scrollable Updatable
leminhvuong
 
Scrollable Updatable
phanleson
 
Executing Sql Commands
leminhvuong
 
Executing Sql Commands
phanleson
 
30 5 Database Jdbc
phanleson
 
JDBC – Java Database Connectivity
Information Technology
 
4. Database Connectivity using JDBC .ppt
HITENKHEMANI
 
java4th.pdf bilgisayar mühendisliği bölümü
Smeyyeztrk10
 
JDBC for CSQL Database
jitendral
 
Discuss the scrollable result set in jdbc
manojmanoj218596
 
Jdbc oracle
yazidds2
 
JDBC.ppt JDBC_FM_2012_201JDBC_FM_2012_201
rorebik626
 
JDBC_Template for database connection using Spring
gangishettysaikrishn
 
Jdbc[1]
Fulvio Corno
 
JDBC programming
Fulvio Corno
 
Java 1-contd
Mukesh Tekwani
 
JDBC (2).ppt
manvibaunthiyal1
 
Java Databse Connectvity- Alex Jose
Dipayan Sarkar
 
Ad

More from phuphax (8)

PDF
GPS Tracking by Tracking.in.th
phuphax
 
PPT
KMUTNB - Internet Programming 5/7
phuphax
 
PPT
KMUTNB - Internet Programming 7/7
phuphax
 
PPT
KMUTNB - Internet Programming 5/7
phuphax
 
PPT
KMUTNB - Internet Programming 4/7
phuphax
 
PPT
KMUTNB - Internet Programming 3/7
phuphax
 
PPT
KMUTNB - Internet Programming 2/7
phuphax
 
PPT
KMUTNB - Internet Programming 1/7
phuphax
 
GPS Tracking by Tracking.in.th
phuphax
 
KMUTNB - Internet Programming 5/7
phuphax
 
KMUTNB - Internet Programming 7/7
phuphax
 
KMUTNB - Internet Programming 5/7
phuphax
 
KMUTNB - Internet Programming 4/7
phuphax
 
KMUTNB - Internet Programming 3/7
phuphax
 
KMUTNB - Internet Programming 2/7
phuphax
 
KMUTNB - Internet Programming 1/7
phuphax
 

Recently uploaded (20)

PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 

KMUTNB - Internet Programming 6/7

  • 1. JSP&DB Programming By: Mr. PHUPHA PUNYAPOTASAKUL ( ภูผา ปัญญาโพธาสกุล )
  • 3. JDBC Connect to a data source, like a database Send queries and update statements to the database Retrieve and process the results received from the database in answer to your query
  • 4. Establish connection Initialize driver Class . forName ( driver ) ; Create Connection Connection conn = DriverManager . getConnection ( url,user,password ) ; Each JDBC Vendor may use different driver class name and url
  • 5. Driver class name and URL example Oracle 10i driver = oracle . jdbc . driver . OracleDriver url = jdbc : oracle : thin : @ // {DBSERVER} : 1521 / {DBNAME} MySQL 4 . x, 5 . x driver = com . mysql . jdbc . Driver url = jdbc : mysql :// {DBSERVER} / {DBNAME} MS SQLServer 2000, 2005 driver = com . microsoft . sqlserver . jdbc . SQLServerDriver url = jdbc : sqlserver :// {DBSERVER} : 1433;databaseName = {DBNAME};integratedSecurity = false;
  • 6. Create statement and execute SQL command Create statement Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY ) ; Execute Update stmt.execut eUpdate ( sql ); Execute Query ResultSet rs = stmt . executeQuery ( sql ) ;
  • 7. ResultSet type TYPE_FORWARD_ONLY — The result set is not scrollable; its cursor moves forward only, from before the first row to after the last row. The rows contained in the result set depend on how the underlying database materializes the results. That is, it contains the rows that satisfy the query at either the time the query is executed or as the rows are retrieved. TYPE_SCROLL_INSENSITIVE — The result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position . TYPE_SCROLL_SENSITIVE — The result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position.
  • 9. ResultSet movement next () - moves the cursor forward one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned after the last row. previous () - moves the cursor backwards one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned before the first row. first () - moves the cursor to the first row in the ResultSet object. Returns true if the cursor is now positioned on the first row and false if the ResultSet object does not contain any rows. last() - moves the cursor to the last row in the ResultSet object . Returns true if the cursor is now positioned on the last row and false if the ResultSet object does not contain any rows .
  • 10. ResultSet movement beforeFirst() - positions the cursor at the start of the ResultSet object, before the first row . If the ResultSet object does not contain any rows, this method has no effect . afterLast() - positions the cursor at the end of the ResultSet object, after the last row . If the ResultSet object does not contain any rows, this method has no effect . relative(int rows) - moves the cursor relative to its current position . absolute(int row) - positions the cursor on the row - th row of the ResultSet object .
  • 11. Retrieving data Data type conversion getString() getInt() getFloat() getDate() etc. 2 ways to retrieve data e.g. select product_name from product By column name getString("product_name"); By column index (start from 1) getString(1);
  • 12. Updating data Only if using CONCUR_UPDATABLE Not all JDBC Driver support this mode Data type conversion upateString() updateInt() updateFloat() updateDate() etc. Be able to use both column name and index
  • 13. Updating data To insert a new record rs.moveToInsertRow() rs.updateString(1,"XXX"); rs.insertRow(); To update a record //move to expected record rs.updateString(1,"XXX"); rs.updateRow(); To delete a record //move to expected record rs.deleteRow();
  • 14. Exception handling Connection conn = null; Statement stmt = null; ResultSet rs = null; try{ ... }catch ( SQLException ex ) { String sqlErr ="" ; while ( ex != null ) { sqlErr = sqlErr + " \nMessage : " + ex . getMessage () ; sqlErr = sqlErr + " \nSQLState : " + ex . getSQLState () ; sqlErr = sqlErr + " \nErrorCode : " + ex . getErrorCode () ; sqlErr = sqlErr + " \n -----------------------------------------------------------" ; ex = ex . getNextException () ; } System . out . println ( sqlErr ) ; }catch ( Exception ex ) { ex . printStackTrace () ; }finally{ try{ if ( rs != null ) rs . close () ; }catch ( Exception e ) {} try{ if ( stmt != null ) stmt . close () ; }catch ( Exception e ) {} try{ if ( conn != null ) conn . close () ; }catch ( Exception e ) {} }
  • 15. Prepared Statement Create Statement PreparedStatement pstmt = conn . prepareStatement ( sql,rtype,concur ) ; SQL with parameter using "?" E.g. select * from product where product_id=? and is_enable=? Set parameter value setString() setFloat() setInt() setDate()
  • 16. Prepared Statement Use parameter index only - can't use column name (start from 1) pstmt.setString(1,"XXX"); Execute query or update normally ResultSet rs=pstmt.executeQuery(); pstmt.executeUpdate(); Re-usable