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
lathasiva
 
PPT
java jdbc connection
Waheed Warraich
 
PDF
22jdbc
Adil Jafri
 
PDF
Jdbc[1]
Fulvio Corno
 
PPS
Jdbc example program with access and MySql
kamal kotecha
 
KEY
JDBC Basics (In 20 Minutes Flat)
Craig Dickson
 
PDF
Introduction to JDBC and database access in web applications
Fulvio Corno
 
PPTX
JDBC ppt
Rohit Jain
 
Jdbc
lathasiva
 
java jdbc connection
Waheed Warraich
 
22jdbc
Adil Jafri
 
Jdbc[1]
Fulvio Corno
 
Jdbc example program with access and MySql
kamal kotecha
 
JDBC Basics (In 20 Minutes Flat)
Craig Dickson
 
Introduction to JDBC and database access in web applications
Fulvio Corno
 
JDBC ppt
Rohit Jain
 

What's hot (19)

PPT
Jdbc sasidhar
Sasidhar Kothuru
 
PDF
Jdbc
mishaRani1
 
PPT
JDBC – Java Database Connectivity
Information Technology
 
PPT
JDBC Java Database Connectivity
Ranjan Kumar
 
PPT
Java database connectivity with MYSQL
Adil Mehmoood
 
PPTX
1. java database connectivity (jdbc)
Fad Zulkifli
 
PPTX
Jdbc in servlets
Nuha Noor
 
PPT
Jdbc
phanleson
 
PDF
The Ring programming language version 1.5.2 book - Part 27 of 181
Mahmoud Samir Fayed
 
PPT
Java Database Connectivity
backdoor
 
PDF
10 jdbc
snopteck
 
PPT
JDBC Tutorial
Information Technology
 
PDF
Introduction to JDBC and JDBC Drivers
Kumar
 
PDF
Jdbc
haribee2000
 
PDF
Advance Java Practical file
varun arora
 
PDF
Core Java Programming Language (JSE) : Chapter XIII - JDBC
WebStackAcademy
 
PPS
Jdbc session01
Niit Care
 
Jdbc sasidhar
Sasidhar Kothuru
 
JDBC – Java Database Connectivity
Information Technology
 
JDBC Java Database Connectivity
Ranjan Kumar
 
Java database connectivity with MYSQL
Adil Mehmoood
 
1. java database connectivity (jdbc)
Fad Zulkifli
 
Jdbc in servlets
Nuha Noor
 
Jdbc
phanleson
 
The Ring programming language version 1.5.2 book - Part 27 of 181
Mahmoud Samir Fayed
 
Java Database Connectivity
backdoor
 
10 jdbc
snopteck
 
JDBC Tutorial
Information Technology
 
Introduction to JDBC and JDBC Drivers
Kumar
 
Advance Java Practical file
varun arora
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
WebStackAcademy
 
Jdbc session01
Niit Care
 
Ad

Similar to Jdbc day-1 (20)

PPT
JDBC Connecticity.ppt
Swapnil Kale
 
PPTX
Jdbc ppt
sandeep54552
 
PDF
Lecture17
vantinhkhuc
 
PPTX
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
Indu32
 
PPTX
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
Indu32
 
PDF
Java JDBC
Jussi Pohjolainen
 
PDF
1586279370_Bsc(P)-VI-InternetTechnologies-3.pdf
RoopaRathod2
 
PPTX
Lecture 1. java database connectivity
Waheedullah Suliman Khail
 
PPTX
Jdbc
Indu Lata
 
PPT
Jdbc oracle
yazidds2
 
PPT
Jdbc
smvdurajesh
 
PPT
jdbc_presentation.ppt
DrMeenakshiS
 
PPTX
JDBC
Balwinder Kumar
 
PPTX
Jdbc Java Programming
chhaichivon
 
PPTX
Amr Mohamed Abd Elhamid_JAVA_JDBCData.pptx
SaadAliEissa
 
PPTX
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
VENKATESHBHAT25
 
PDF
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
PPT
Data Access with JDBC
BG Java EE Course
 
PPT
Jdbc drivers
Prabhat gangwar
 
JDBC Connecticity.ppt
Swapnil Kale
 
Jdbc ppt
sandeep54552
 
Lecture17
vantinhkhuc
 
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
Indu32
 
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
Indu32
 
1586279370_Bsc(P)-VI-InternetTechnologies-3.pdf
RoopaRathod2
 
Lecture 1. java database connectivity
Waheedullah Suliman Khail
 
Jdbc
Indu Lata
 
Jdbc oracle
yazidds2
 
jdbc_presentation.ppt
DrMeenakshiS
 
Jdbc Java Programming
chhaichivon
 
Amr Mohamed Abd Elhamid_JAVA_JDBCData.pptx
SaadAliEissa
 
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
VENKATESHBHAT25
 
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
Data Access with JDBC
BG Java EE Course
 
Jdbc drivers
Prabhat gangwar
 
Ad

More from Soham Sengupta (20)

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

Recently uploaded (20)

PPT
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
PDF
Immersive experiences: what Pharo users do!
ESUG
 
PDF
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PDF
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
PDF
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PDF
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
PDF
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
PDF
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
PPTX
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
Immersive experiences: what Pharo users do!
ESUG
 
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
Activate_Methodology_Summary presentatio
annapureddyn
 
Exploring AI Agents in Process Industries
amoreira6
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
Role Of Python In Programing Language.pptx
jaykoshti048
 
Presentation about variables and constant.pptx
kr2589474
 
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 

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, [email protected] 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, [email protected] 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, [email protected] 3
  • 4. STEP-1: Ctrl Panel>Admin Tools>Data Sources (ODBC) Monday, October 13, [email protected] 4
  • 5. STEP-2: Go to System DSN tab and then click on Add Button Monday, October 13, [email protected] 5
  • 6. STEP-3: Select the Driver and Click Finish Button • Select the required Driver that you need Monday, October 13, [email protected] 6
  • 7. STEP-4: Type the Data Source Name (DSN) • and browse the Database (here IBM.mdb) and click OK Monday, October 13, [email protected] 7
  • 8. Final Step: Now click OK, • and ibm will appear under System DSN TAB Monday, October 13, [email protected] 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, [email protected] 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, [email protected] 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, [email protected] 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, [email protected] 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, [email protected] 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, [email protected] 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, [email protected] 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, [email protected] 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, [email protected] 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, [email protected] 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, [email protected] 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, [email protected] 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, [email protected] 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, [email protected] 22