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

What's hot

Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
Sasidhar Kothuru
 
Jdbc
JdbcJdbc
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
Ranjan Kumar
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
Adil Mehmoood
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
Fad Zulkifli
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
Nuha Noor
 
The Ring programming language version 1.5.2 book - Part 27 of 181
The Ring programming language version 1.5.2 book - Part 27 of 181The Ring programming language version 1.5.2 book - Part 27 of 181
The Ring programming language version 1.5.2 book - Part 27 of 181
Mahmoud Samir Fayed
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivitybackdoor
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
Kumar
 
Jdbc
JdbcJdbc
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
varun arora
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Core Java Programming Language (JSE) : Chapter XIII -  JDBCCore Java Programming Language (JSE) : Chapter XIII -  JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBC
WebStackAcademy
 
Jdbc session01
Jdbc session01Jdbc session01
Jdbc session01Niit Care
 

What's hot (19)

Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
Jdbc
JdbcJdbc
Jdbc
 
The Ring programming language version 1.5.2 book - Part 27 of 181
The Ring programming language version 1.5.2 book - Part 27 of 181The Ring programming language version 1.5.2 book - Part 27 of 181
The Ring programming language version 1.5.2 book - Part 27 of 181
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
Jdbc
JdbcJdbc
Jdbc
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Core Java Programming Language (JSE) : Chapter XIII -  JDBCCore Java Programming Language (JSE) : Chapter XIII -  JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBC
 
Jdbc session01
Jdbc session01Jdbc session01
Jdbc session01
 

Similar to Jdbc day-1

JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
Swapnil Kale
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
sandeep54552
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
Waheedullah Suliman Khail
 
Jdbc
JdbcJdbc
Jdbc
Indu Lata
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
DrMeenakshiS
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
chhaichivon
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
BG Java EE Course
 
Jdbc drivers
Jdbc driversJdbc drivers
Jdbc drivers
Prabhat gangwar
 
Chapter vii(accessing databases with jdbc)
Chapter vii(accessing databases with jdbc)Chapter vii(accessing databases with jdbc)
Chapter vii(accessing databases with jdbc)
Chhom Karath
 
High Performance Jdbc
High Performance JdbcHigh Performance Jdbc
High Performance JdbcSam Pattsin
 
JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
manvibaunthiyal1
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
Hemo Chella
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)Maher Abdo
 

Similar to Jdbc day-1 (20)

JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Lecture17
Lecture17Lecture17
Lecture17
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
Jsp project module
Jsp project moduleJsp project module
Jsp project module
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Jdbc
JdbcJdbc
Jdbc
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
JDBC
JDBCJDBC
JDBC
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Jdbc drivers
Jdbc driversJdbc drivers
Jdbc drivers
 
Chapter vii(accessing databases with jdbc)
Chapter vii(accessing databases with jdbc)Chapter vii(accessing databases with jdbc)
Chapter vii(accessing databases with jdbc)
 
High Performance Jdbc
High Performance JdbcHigh Performance Jdbc
High Performance Jdbc
 
JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 

More from Soham Sengupta

Spring method-level-secuirty
Spring method-level-secuirtySpring method-level-secuirty
Spring method-level-secuirty
Soham Sengupta
 
Spring security mvc-1
Spring security mvc-1Spring security mvc-1
Spring security mvc-1
Soham Sengupta
 
JavaScript event handling assignment
JavaScript  event handling assignment JavaScript  event handling assignment
JavaScript event handling assignment
Soham Sengupta
 
Networking assignment 2
Networking assignment 2Networking assignment 2
Networking assignment 2
Soham Sengupta
 
Networking assignment 1
Networking assignment 1Networking assignment 1
Networking assignment 1
Soham Sengupta
 
Sohams cryptography basics
Sohams cryptography basicsSohams cryptography basics
Sohams cryptography basics
Soham Sengupta
 
Network programming1
Network programming1Network programming1
Network programming1
Soham Sengupta
 
JSR-82 Bluetooth tutorial
JSR-82 Bluetooth tutorialJSR-82 Bluetooth tutorial
JSR-82 Bluetooth tutorial
Soham Sengupta
 
Xmpp and java
Xmpp and javaXmpp and java
Xmpp and java
Soham Sengupta
 
Core java day2
Core java day2Core java day2
Core java day2
Soham Sengupta
 
Core java day1
Core java day1Core java day1
Core java day1
Soham Sengupta
 
Core java day4
Core java day4Core java day4
Core java day4
Soham Sengupta
 
Core java day5
Core java day5Core java day5
Core java day5
Soham Sengupta
 
Exceptions
ExceptionsExceptions
Exceptions
Soham Sengupta
 
Java.lang.object
Java.lang.objectJava.lang.object
Java.lang.object
Soham Sengupta
 
Jsp1
Jsp1Jsp1
Soham web security
Soham web securitySoham web security
Soham web security
Soham Sengupta
 
Html tables and_javascript
Html tables and_javascriptHtml tables and_javascript
Html tables and_javascript
Soham Sengupta
 
Html javascript
Html javascriptHtml javascript
Html javascript
Soham Sengupta
 
Java script
Java scriptJava script
Java script
Soham Sengupta
 

More from Soham Sengupta (20)

Spring method-level-secuirty
Spring method-level-secuirtySpring method-level-secuirty
Spring method-level-secuirty
 
Spring security mvc-1
Spring security mvc-1Spring security mvc-1
Spring security mvc-1
 
JavaScript event handling assignment
JavaScript  event handling assignment JavaScript  event handling assignment
JavaScript event handling assignment
 
Networking assignment 2
Networking assignment 2Networking assignment 2
Networking assignment 2
 
Networking assignment 1
Networking assignment 1Networking assignment 1
Networking assignment 1
 
Sohams cryptography basics
Sohams cryptography basicsSohams cryptography basics
Sohams cryptography basics
 
Network programming1
Network programming1Network programming1
Network programming1
 
JSR-82 Bluetooth tutorial
JSR-82 Bluetooth tutorialJSR-82 Bluetooth tutorial
JSR-82 Bluetooth tutorial
 
Xmpp and java
Xmpp and javaXmpp and java
Xmpp and java
 
Core java day2
Core java day2Core java day2
Core java day2
 
Core java day1
Core java day1Core java day1
Core java day1
 
Core java day4
Core java day4Core java day4
Core java day4
 
Core java day5
Core java day5Core java day5
Core java day5
 
Exceptions
ExceptionsExceptions
Exceptions
 
Java.lang.object
Java.lang.objectJava.lang.object
Java.lang.object
 
Jsp1
Jsp1Jsp1
Jsp1
 
Soham web security
Soham web securitySoham web security
Soham web security
 
Html tables and_javascript
Html tables and_javascriptHtml tables and_javascript
Html tables and_javascript
 
Html javascript
Html javascriptHtml javascript
Html javascript
 
Java script
Java scriptJava script
Java script
 

Recently uploaded

top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 

Recently uploaded (20)

top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 

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