SlideShare a Scribd company logo
JDBC: What & Why? 
As we all know, Java is platform independent, 
there must be some means to have some ready-to- 
hand way, specifically some API to handle 
Database activities that can interface between 
your Java Code and an RDBMS and perform the 
desired SQL. This is known as Java DataBase 
Connectivity (JDBC). JDBC-version 2.x defines 2 
packages, java.sql and javax.sql that provide the 
basement of a JDBC API 
Monday, October 13, 2014sohamsengupta@yahoo.com 1
JDBC Drivers & Types 
• As JDBC plays the role to interface between the 
RDBMS and Java Code, from the Database’s part, 
there must be some vendor specific utilities that 
will cooperate with JDBC. These are known as 
JDBC Drivers, having 4 Types, Type-1 to Type-4. 
We, however, must avoid theoretical discussion 
about them but shall deal with Type-1, also known 
as JDBC-ODBC Bridge, and Type-4, also known 
as Pure Java Driver. So, on to the next slide… 
Monday, October 13, 2014sohamsengupta@yahoo.com 2
Primary Steps to code JDBC with 
ODBC Bridge Driver 
• STEP-1: Load the Driver Class, coded as 
• Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 
• This statement loads the said class in memory, 
thus allowing your code to succeed. 
• STEP-2: Obtain a Database Connection 
represented by java.sql.Connection interface, to 
be obtained through code as 
• Connection 
conn=DriverManager.getConnection(“jdbc:odbc:ibm”); 
• Here “jdbc:odbc:ibm” is the connection 
String, where ibm is set up through 
Control Panel as follows… 
Monday, October 13, 2014sohamsengupta@yahoo.com 3
STEP-1: Ctrl Panel>Admin 
Tools>Data Sources (ODBC) 
Monday, October 13, 2014sohamsengupta@yahoo.com 4
STEP-2: Go to System DSN tab 
and then click on Add Button 
Monday, October 13, 2014sohamsengupta@yahoo.com 5
STEP-3: Select the Driver and Click 
Finish Button 
• Select the required Driver that you need 
Monday, October 13, 2014sohamsengupta@yahoo.com 6
STEP-4: Type the Data Source 
Name (DSN) 
• and browse the Database (here IBM.mdb) 
and click OK 
Monday, October 13, 2014sohamsengupta@yahoo.com 7
Final Step: Now click OK, 
• and ibm will appear under System DSN 
TAB 
Monday, October 13, 2014sohamsengupta@yahoo.com 8
Creating A Table in an MS-Access (.mdb) 
Database: First import java.sql.* to access 
the JDBC API 
• static void createTable(String strTableName) throws Exception{ 
• Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
• Connection 
conn=DriverManager.getConnection("jdbc:odbc:ibm"); 
• Statement st=conn.createStatement(); 
• st.executeUpdate("create table "+strTableName+"(name 
varchar(30),id varchar(20),marks INTEGER)"); 
• st.close(); 
• conn.close(); 
• System.out.println("Table "+strTableName+" created 
successfully!"); 
• } 
Monday, October 13, 2014sohamsengupta@yahoo.com 9
How to insert a Row 
• static void insertRow(String strId,String strName,int marks) throws 
Exception{ 
• Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
• Connection conn=DriverManager.getConnection("jdbc:odbc:ibm"); 
• PreparedStatement ps=conn.prepareStatement("insert into 
StudentTable (id,name,marks) values(?,?,?)"); 
• ps.setString(1,strId); 
• ps.setString(2,strName); 
• ps.setInt(3,marks); 
• ps.executeUpdate(); 
• System.out.println(ps.getResultSet()); 
• ps.close(); 
• conn.close(); 
• System.out.println("Row inserted successfully!"); 
• } 
Monday, October 13, 2014sohamsengupta@yahoo.com 10
How to fetch All Rows of a Table 
static void selectAllRowsOtherMethod() throws Exception{ 
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
Connection 
conn=DriverManager.getConnection("jdbc:odbc:ibm"); 
Statement st=conn.createStatement(); 
ResultSet rs=st.executeQuery("select * from StudentTable"); 
while(rs.next()){ 
System.out.println(rs.getString("id")+"t"+rs.getString("name") 
+"t"+rs.getInt("marks")); 
} 
st.close(); 
conn.close(); 
} 
Monday, October 13, 2014sohamsengupta@yahoo.com 11
Another Approach 
• static void selectAllRows() throws Exception{ 
• Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
• Connection 
conn=DriverManager.getConnection("jdbc:odbc:ibm"); 
• Statement st=conn.createStatement(); 
• st.execute("select * from StudentTable"); 
• ResultSet rs=st.getResultSet(); 
• while(rs.next()){ 
• System.out.println(rs.getString("id") 
+"t"+rs.getString("name")+"t"+rs.getInt("marks")); 
• } 
• st.close(); 
• conn.close(); 
• } 
Monday, October 13, 2014sohamsengupta@yahoo.com 12
How to fetch a single row 
• static void selectAStudent(String strId) throws Exception{ 
• Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
• Connection 
conn=DriverManager.getConnection("jdbc:odbc:ibm"); 
• PreparedStatement ps=conn.prepareStatement("select * from 
StudentTable where id=?"); 
• ps.setString(1,strId); 
• ResultSet rs=ps.executeQuery(); 
• if(rs.next()){ 
System.out.println(rs.getString("name")+"t"+rs.getString("id") 
+"t"+rs.getInt("marks")); 
• }else{ System.out.println(strId+" Not found!"); 
• } 
• ps.close(); 
• conn.close(); 
• } 
Monday, October 13, 2014sohamsengupta@yahoo.com 13
Update Rows 
• static void updateAStudent(String strId,int intNewMarks) 
throws Exception{ 
• Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
• Connection 
conn=DriverManager.getConnection("jdbc:odbc:ibm"); 
• PreparedStatement ps=conn.prepareStatement("update 
StudentTable set marks=? where id=?"); 
• ps.setInt(1,intNewMarks); 
• ps.setString(2,strId); 
• int intStatus=ps.executeUpdate(); 
• System.out.println(intStatus+" Row(s) updated"); 
• ps.close(); 
• conn.close(); 
• } 
Monday, October 13, 2014sohamsengupta@yahoo.com 14
Update Rows : Another Approach 
• static void updateARowOtherMethod(int intNewMarks,String 
strNewName) throws Exception{ 
• Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
• Connection 
conn=DriverManager.getConnection("jdbc:odbc:ibm"); 
• Statement 
st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITI 
VE,ResultSet.CONCUR_UPDATABLE); 
• ResultSet rs=st.executeQuery("select marks,name from 
StudentTable order by id"); 
• rs.absolute(2); 
• rs.updateInt(1,intNewMarks); 
• rs.updateString(2,strNewName); 
• rs.updateRow(); 
• st.close(); 
• conn.close(); 
• System.out.println("Updated successfully"); 
• } 
Monday, October 13, 2014sohamsengupta@yahoo.com 15
Finally Calling these methods 
• public static void main(String[]args) throws Exception{ 
• createTable("StudentTable"); 
insertRow("it/00/57","Soham Sengupta",940); 
• insertRow("it/00/01","Manas Ghosh",620); 
• insertRow("it/00/2","Tanay Das",657); 
• insertRow("it/00/63","Abhisek Biswas",721); 
• selectAllRowsOtherMethod(); 
• selectAStudent("it/00/02"); 
• updateAStudent("it/00/1",755); 
• updateARowOtherMethod(102,"Tanoy Dash"); 
• } 
Monday, October 13, 2014sohamsengupta@yahoo.com 16
Some important features 
• After establishing a Connection, we have to create 
a Statement or PreparedStatement object that 
would execute the desired SQL. 
• There are 3 methods: execute(), executeUpdate() 
and executeQuery(). The first 2 return int indicating 
the number of rows updated/ otherwise, whereas 
the last one returns a java.sql.ResultSet that holds 
the data. At first it points to the BOC so we have to 
call next() method that returns false when no data 
is available else true. Also, next() causes the cursor 
to advance one step. Some special ResultSets may 
fetch data in either direction. 
Monday, October 13, 2014sohamsengupta@yahoo.com 17
Executing SQL through JDBC 
• SQL, though may differ from an RDBMS to 
another, always involves 4 basic operations 
known as CRUD (Create, Read, Update, 
Delete). 
• Basically there are 2 categories of options; first, 
Write operation involving create, insert, update, 
delete etc… and second, READ operation. We 
perform these through Statement and/or 
PreparedStatement. 
• The next slide depicts how basic SQL can be 
executed through these objects. 
Monday, October 13, 2014sohamsengupta@yahoo.com 18
A Simple Insert Command 
• Assuming a table, StudentTable comprising 3 fields: id 
varchar(30), name varchar(40) and marks INTEGER, we 
may insert the data set (‘it/00/57’, ‘Soham’, 940) with the 
command: 
• Insert into StudentTable (id,name,marks) values(‘it/00/57’, ‘Soham’, 
940); 
• If we represent the above by a Java String object and the column values 
being termed by variables strName, strId and intMarks, then, the SQL 
becomes, in code, 
• String strSQL=“insert into StudentTable (id,name,marks) values(‘”+ 
strId+”’,’”+strName+”’,”+intMarks+”)”; 
• Here, + operator concatenates the SQL with column values replaced 
by corresponding variables. We, however, must be aware to close an 
open parenthesis and/or a single-quote( ‘ ). This is to be executed with 
a java.sql.Statement object. 
• But this is a nasty coding, and should be avoided with 
PreparedStatement decsribed in the next slide 
Monday, October 13, 2014sohamsengupta@yahoo.com 19
How PreparedStatement Betters 
Clumsiness in code 
• After loading the driver class, and obtaining the 
Connection object (say, conn), we should code 
as : 
• PreparedStatement ps=conn.prepareStatement(“insert into 
StudentTable (id,name,marks) values(?,?,?)”); 
• ps.setString(1,strId); 
• ps.setString(2,strName); 
• ps.setInt(3,intMarks); 
• ps.executeUpdate(); 
• What we should keep in mind is, index the setters correctly, for 
example, ps.setString(1,strId) as I’m inserting the column id at 
1, name at 2 and marks at 3. 
• Thus, PreparedStatement can be used for other SQL 
commands, too, like select commands et al. 
Monday, October 13, 2014sohamsengupta@yahoo.com 20
Transaction Failure Management 
(TFM) 
• The Software market extensively uses RDBMS and 
it’s quite obvious those built on Java Technology 
would involve JDBC. Also, what goes without saying 
is, these Software packages involve highly delicate 
Transactions like Banking etc. and hence must 
conform to the maximum level of TFM, else the 
entire ACID paradigms would be violated causing 
much a chaos. JDBC API provides with built-in TFM 
at coding level. You must be aware that if any thing 
goes wrong in a JDBC transaction, checked 
Exception like java.sql.SQLException and others are 
thrown. So, we put the entire ATOMIC Transaction 
code under a try-catch Exception handling scanner. 
Monday, October 13, 2014sohamsengupta@yahoo.com 21
TFM Coding Style 
Connection conn; 
try{ 
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 
conn=DriverManager.getConnection(“jdbc:odbc:dsn”); 
conn.setAutoCommit(false); // don’t coomit until entire done 
… 
… 
conn.commit(); // now, no Exception, thank God, now commit it 
}catch(Throwable t){ 
conn.rollback(); // This makes the system to roll back on 
//Exception 
} 
Monday, October 13, 2014sohamsengupta@yahoo.com 22

More Related Content

PPT
Jdbc
PPT
java jdbc connection
PDF
22jdbc
PDF
Jdbc[1]
PPS
Jdbc example program with access and MySql
KEY
JDBC Basics (In 20 Minutes Flat)
PDF
Introduction to JDBC and database access in web applications
PPTX
JDBC ppt
Jdbc
java jdbc connection
22jdbc
Jdbc[1]
Jdbc example program with access and MySql
JDBC Basics (In 20 Minutes Flat)
Introduction to JDBC and database access in web applications
JDBC ppt

What's hot (19)

PPT
Jdbc sasidhar
PDF
PPT
JDBC – Java Database Connectivity
PPT
JDBC Java Database Connectivity
PPT
Java database connectivity with MYSQL
PPTX
1. java database connectivity (jdbc)
PPTX
Jdbc in servlets
PPT
Jdbc
PDF
The Ring programming language version 1.5.2 book - Part 27 of 181
PPT
Java Database Connectivity
PDF
10 jdbc
PPT
JDBC Tutorial
PDF
Introduction to JDBC and JDBC Drivers
PDF
PDF
Advance Java Practical file
PDF
Core Java Programming Language (JSE) : Chapter XIII - JDBC
PPS
Jdbc session01
Jdbc sasidhar
JDBC – Java Database Connectivity
JDBC Java Database Connectivity
Java database connectivity with MYSQL
1. java database connectivity (jdbc)
Jdbc in servlets
Jdbc
The Ring programming language version 1.5.2 book - Part 27 of 181
Java Database Connectivity
10 jdbc
JDBC Tutorial
Introduction to JDBC and JDBC Drivers
Advance Java Practical file
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Jdbc session01
Ad

Similar to Jdbc day-1 (20)

PPTX
Jdbc presentation
PDF
PPT
JDBC.ppt
PPTX
Database Programming Techniques
PPT
Jdbc oracle
PPTX
Jdbc
PPTX
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
DOC
Java database connectivity notes for undergraduate
PPTX
Module 5 jdbc.ppt
PDF
Presentation for java data base connectivity
PDF
Jdbc Complete Notes by Java Training Center (Som Sir)
PPTX
Amr Mohamed Abd Elhamid_JAVA_JDBCData.pptx
PPT
Jdbc (database in java)
PPTX
Jdbc Java Programming
PDF
java arlow jdbc tutorial(java programming tutorials)
PDF
Java OOP Programming language (Part 8) - Java Database JDBC
PPT
PPTX
JDBC PPT(4).pptx java Database Connectivity
PPT
11. jdbc
PPT
JDBC.ppt
Jdbc presentation
JDBC.ppt
Database Programming Techniques
Jdbc oracle
Jdbc
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
Java database connectivity notes for undergraduate
Module 5 jdbc.ppt
Presentation for java data base connectivity
Jdbc Complete Notes by Java Training Center (Som Sir)
Amr Mohamed Abd Elhamid_JAVA_JDBCData.pptx
Jdbc (database in java)
Jdbc Java Programming
java arlow jdbc tutorial(java programming tutorials)
Java OOP Programming language (Part 8) - Java Database JDBC
JDBC PPT(4).pptx java Database Connectivity
11. jdbc
JDBC.ppt
Ad

More from Soham Sengupta (20)

PPTX
Spring method-level-secuirty
PPTX
Spring security mvc-1
PDF
JavaScript event handling assignment
PDF
Networking assignment 2
PDF
Networking assignment 1
PPT
Sohams cryptography basics
PPT
Network programming1
PPT
JSR-82 Bluetooth tutorial
PPSX
Xmpp and java
PPT
Core java day2
PPT
Core java day1
PPT
Core java day4
PPT
Core java day5
PPT
Exceptions
PPSX
Java.lang.object
PPTX
Soham web security
PPTX
Html tables and_javascript
PPT
Html javascript
PPT
Java script
Spring method-level-secuirty
Spring security mvc-1
JavaScript event handling assignment
Networking assignment 2
Networking assignment 1
Sohams cryptography basics
Network programming1
JSR-82 Bluetooth tutorial
Xmpp and java
Core java day2
Core java day1
Core java day4
Core java day5
Exceptions
Java.lang.object
Soham web security
Html tables and_javascript
Html javascript
Java script

Recently uploaded (20)

PDF
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
PDF
Autodesk AutoCAD Crack Free Download 2025
PPTX
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Download FL Studio Crack Latest version 2025 ?
PPTX
Computer Software and OS of computer science of grade 11.pptx
PPTX
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
PPTX
Advanced SystemCare Ultimate Crack + Portable (2025)
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PPTX
Oracle Fusion HCM Cloud Demo for Beginners
PDF
How AI/LLM recommend to you ? GDG meetup 16 Aug by Fariman Guliev
PPTX
Weekly report ppt - harsh dattuprasad patel.pptx
PDF
CapCut Video Editor 6.8.1 Crack for PC Latest Download (Fully Activated) 2025
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
history of c programming in notes for students .pptx
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
Autodesk AutoCAD Crack Free Download 2025
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
Odoo Companies in India – Driving Business Transformation.pdf
Download FL Studio Crack Latest version 2025 ?
Computer Software and OS of computer science of grade 11.pptx
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
CHAPTER 2 - PM Management and IT Context
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
Advanced SystemCare Ultimate Crack + Portable (2025)
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Oracle Fusion HCM Cloud Demo for Beginners
How AI/LLM recommend to you ? GDG meetup 16 Aug by Fariman Guliev
Weekly report ppt - harsh dattuprasad patel.pptx
CapCut Video Editor 6.8.1 Crack for PC Latest Download (Fully Activated) 2025
Adobe Illustrator 28.6 Crack My Vision of Vector Design
history of c programming in notes for students .pptx
Why Generative AI is the Future of Content, Code & Creativity?

Jdbc day-1

  • 1. JDBC: What & Why? As we all know, Java is platform independent, there must be some means to have some ready-to- hand way, specifically some API to handle Database activities that can interface between your Java Code and an RDBMS and perform the desired SQL. This is known as Java DataBase Connectivity (JDBC). JDBC-version 2.x defines 2 packages, java.sql and javax.sql that provide the basement of a JDBC API Monday, October 13, 2014sohamsengupta@yahoo.com 1
  • 2. JDBC Drivers & Types • As JDBC plays the role to interface between the RDBMS and Java Code, from the Database’s part, there must be some vendor specific utilities that will cooperate with JDBC. These are known as JDBC Drivers, having 4 Types, Type-1 to Type-4. We, however, must avoid theoretical discussion about them but shall deal with Type-1, also known as JDBC-ODBC Bridge, and Type-4, also known as Pure Java Driver. So, on to the next slide… Monday, October 13, 2014sohamsengupta@yahoo.com 2
  • 3. Primary Steps to code JDBC with ODBC Bridge Driver • STEP-1: Load the Driver Class, coded as • Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); • This statement loads the said class in memory, thus allowing your code to succeed. • STEP-2: Obtain a Database Connection represented by java.sql.Connection interface, to be obtained through code as • Connection conn=DriverManager.getConnection(“jdbc:odbc:ibm”); • Here “jdbc:odbc:ibm” is the connection String, where ibm is set up through Control Panel as follows… Monday, October 13, 2014sohamsengupta@yahoo.com 3
  • 4. STEP-1: Ctrl Panel>Admin Tools>Data Sources (ODBC) Monday, October 13, 2014sohamsengupta@yahoo.com 4
  • 5. STEP-2: Go to System DSN tab and then click on Add Button Monday, October 13, 2014sohamsengupta@yahoo.com 5
  • 6. STEP-3: Select the Driver and Click Finish Button • Select the required Driver that you need Monday, October 13, 2014sohamsengupta@yahoo.com 6
  • 7. STEP-4: Type the Data Source Name (DSN) • and browse the Database (here IBM.mdb) and click OK Monday, October 13, 2014sohamsengupta@yahoo.com 7
  • 8. Final Step: Now click OK, • and ibm will appear under System DSN TAB Monday, October 13, 2014sohamsengupta@yahoo.com 8
  • 9. Creating A Table in an MS-Access (.mdb) Database: First import java.sql.* to access the JDBC API • static void createTable(String strTableName) throws Exception{ • Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); • Connection conn=DriverManager.getConnection("jdbc:odbc:ibm"); • Statement st=conn.createStatement(); • st.executeUpdate("create table "+strTableName+"(name varchar(30),id varchar(20),marks INTEGER)"); • st.close(); • conn.close(); • System.out.println("Table "+strTableName+" created successfully!"); • } Monday, October 13, 2014sohamsengupta@yahoo.com 9
  • 10. How to insert a Row • static void insertRow(String strId,String strName,int marks) throws Exception{ • Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); • Connection conn=DriverManager.getConnection("jdbc:odbc:ibm"); • PreparedStatement ps=conn.prepareStatement("insert into StudentTable (id,name,marks) values(?,?,?)"); • ps.setString(1,strId); • ps.setString(2,strName); • ps.setInt(3,marks); • ps.executeUpdate(); • System.out.println(ps.getResultSet()); • ps.close(); • conn.close(); • System.out.println("Row inserted successfully!"); • } Monday, October 13, 2014sohamsengupta@yahoo.com 10
  • 11. How to fetch All Rows of a Table static void selectAllRowsOtherMethod() throws Exception{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn=DriverManager.getConnection("jdbc:odbc:ibm"); Statement st=conn.createStatement(); ResultSet rs=st.executeQuery("select * from StudentTable"); while(rs.next()){ System.out.println(rs.getString("id")+"t"+rs.getString("name") +"t"+rs.getInt("marks")); } st.close(); conn.close(); } Monday, October 13, 2014sohamsengupta@yahoo.com 11
  • 12. Another Approach • static void selectAllRows() throws Exception{ • Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); • Connection conn=DriverManager.getConnection("jdbc:odbc:ibm"); • Statement st=conn.createStatement(); • st.execute("select * from StudentTable"); • ResultSet rs=st.getResultSet(); • while(rs.next()){ • System.out.println(rs.getString("id") +"t"+rs.getString("name")+"t"+rs.getInt("marks")); • } • st.close(); • conn.close(); • } Monday, October 13, 2014sohamsengupta@yahoo.com 12
  • 13. How to fetch a single row • static void selectAStudent(String strId) throws Exception{ • Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); • Connection conn=DriverManager.getConnection("jdbc:odbc:ibm"); • PreparedStatement ps=conn.prepareStatement("select * from StudentTable where id=?"); • ps.setString(1,strId); • ResultSet rs=ps.executeQuery(); • if(rs.next()){ System.out.println(rs.getString("name")+"t"+rs.getString("id") +"t"+rs.getInt("marks")); • }else{ System.out.println(strId+" Not found!"); • } • ps.close(); • conn.close(); • } Monday, October 13, 2014sohamsengupta@yahoo.com 13
  • 14. Update Rows • static void updateAStudent(String strId,int intNewMarks) throws Exception{ • Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); • Connection conn=DriverManager.getConnection("jdbc:odbc:ibm"); • PreparedStatement ps=conn.prepareStatement("update StudentTable set marks=? where id=?"); • ps.setInt(1,intNewMarks); • ps.setString(2,strId); • int intStatus=ps.executeUpdate(); • System.out.println(intStatus+" Row(s) updated"); • ps.close(); • conn.close(); • } Monday, October 13, 2014sohamsengupta@yahoo.com 14
  • 15. Update Rows : Another Approach • static void updateARowOtherMethod(int intNewMarks,String strNewName) throws Exception{ • Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); • Connection conn=DriverManager.getConnection("jdbc:odbc:ibm"); • Statement st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITI VE,ResultSet.CONCUR_UPDATABLE); • ResultSet rs=st.executeQuery("select marks,name from StudentTable order by id"); • rs.absolute(2); • rs.updateInt(1,intNewMarks); • rs.updateString(2,strNewName); • rs.updateRow(); • st.close(); • conn.close(); • System.out.println("Updated successfully"); • } Monday, October 13, 2014sohamsengupta@yahoo.com 15
  • 16. Finally Calling these methods • public static void main(String[]args) throws Exception{ • createTable("StudentTable"); insertRow("it/00/57","Soham Sengupta",940); • insertRow("it/00/01","Manas Ghosh",620); • insertRow("it/00/2","Tanay Das",657); • insertRow("it/00/63","Abhisek Biswas",721); • selectAllRowsOtherMethod(); • selectAStudent("it/00/02"); • updateAStudent("it/00/1",755); • updateARowOtherMethod(102,"Tanoy Dash"); • } Monday, October 13, 2014sohamsengupta@yahoo.com 16
  • 17. Some important features • After establishing a Connection, we have to create a Statement or PreparedStatement object that would execute the desired SQL. • There are 3 methods: execute(), executeUpdate() and executeQuery(). The first 2 return int indicating the number of rows updated/ otherwise, whereas the last one returns a java.sql.ResultSet that holds the data. At first it points to the BOC so we have to call next() method that returns false when no data is available else true. Also, next() causes the cursor to advance one step. Some special ResultSets may fetch data in either direction. Monday, October 13, 2014sohamsengupta@yahoo.com 17
  • 18. Executing SQL through JDBC • SQL, though may differ from an RDBMS to another, always involves 4 basic operations known as CRUD (Create, Read, Update, Delete). • Basically there are 2 categories of options; first, Write operation involving create, insert, update, delete etc… and second, READ operation. We perform these through Statement and/or PreparedStatement. • The next slide depicts how basic SQL can be executed through these objects. Monday, October 13, 2014sohamsengupta@yahoo.com 18
  • 19. A Simple Insert Command • Assuming a table, StudentTable comprising 3 fields: id varchar(30), name varchar(40) and marks INTEGER, we may insert the data set (‘it/00/57’, ‘Soham’, 940) with the command: • Insert into StudentTable (id,name,marks) values(‘it/00/57’, ‘Soham’, 940); • If we represent the above by a Java String object and the column values being termed by variables strName, strId and intMarks, then, the SQL becomes, in code, • String strSQL=“insert into StudentTable (id,name,marks) values(‘”+ strId+”’,’”+strName+”’,”+intMarks+”)”; • Here, + operator concatenates the SQL with column values replaced by corresponding variables. We, however, must be aware to close an open parenthesis and/or a single-quote( ‘ ). This is to be executed with a java.sql.Statement object. • But this is a nasty coding, and should be avoided with PreparedStatement decsribed in the next slide Monday, October 13, 2014sohamsengupta@yahoo.com 19
  • 20. How PreparedStatement Betters Clumsiness in code • After loading the driver class, and obtaining the Connection object (say, conn), we should code as : • PreparedStatement ps=conn.prepareStatement(“insert into StudentTable (id,name,marks) values(?,?,?)”); • ps.setString(1,strId); • ps.setString(2,strName); • ps.setInt(3,intMarks); • ps.executeUpdate(); • What we should keep in mind is, index the setters correctly, for example, ps.setString(1,strId) as I’m inserting the column id at 1, name at 2 and marks at 3. • Thus, PreparedStatement can be used for other SQL commands, too, like select commands et al. Monday, October 13, 2014sohamsengupta@yahoo.com 20
  • 21. Transaction Failure Management (TFM) • The Software market extensively uses RDBMS and it’s quite obvious those built on Java Technology would involve JDBC. Also, what goes without saying is, these Software packages involve highly delicate Transactions like Banking etc. and hence must conform to the maximum level of TFM, else the entire ACID paradigms would be violated causing much a chaos. JDBC API provides with built-in TFM at coding level. You must be aware that if any thing goes wrong in a JDBC transaction, checked Exception like java.sql.SQLException and others are thrown. So, we put the entire ATOMIC Transaction code under a try-catch Exception handling scanner. Monday, October 13, 2014sohamsengupta@yahoo.com 21
  • 22. TFM Coding Style Connection conn; try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); conn=DriverManager.getConnection(“jdbc:odbc:dsn”); conn.setAutoCommit(false); // don’t coomit until entire done … … conn.commit(); // now, no Exception, thank God, now commit it }catch(Throwable t){ conn.rollback(); // This makes the system to roll back on //Exception } Monday, October 13, 2014sohamsengupta@yahoo.com 22