SlideShare a Scribd company logo
Advance Java Technology
[Java Database Connectivity]
Mali Nayan M
Assistant Professor
Department of Information Technology
Sigma Institute of Engineering
Advance Java Technology 1
ResultSet interface
• The object of ResultSet maintains a cursor pointing to a particular row
of data. Initially, cursor points to before the first row.
• But we can make this object to move forward and backward direction
by passing either TYPE_SCROLL_INSENSITIVE or
TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well
as we can make this object as updatable by:
• Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSE
NSITIVE, ResultSet.CONCUR_UPDATABLE);
Advance Java Technology 2
1) public boolean next(): is used to move the cursor to the one
row next from the current position.
2) public boolean previous(): is used to move the cursor to the one
row previous from the current position.
3) public boolean first(): is used to move the cursor to the first
row in result set object.
4) public boolean last(): is used to move the cursor to the last
row in result set object.
5) public boolean absolute(int row): is used to move the cursor to the
specified row number in the ResultSet
object.
Advance Java Technology 3
6) public boolean relative(int row): is used to move the cursor to the
relative row number in the ResultSet
object, it may be positive or negative.
7) public int getInt(int
columnIndex):
is used to return the data of specified
column index of the current row as int.
8) public int getInt(String
columnName):
is used to return the data of specified
column name of the current row as int.
9) public String getString(int
columnIndex):
is used to return the data of specified
column index of the current row as
String.
10) public String getString(String
columnName):
is used to return the data of specified
column name of the current row as
String.
Advance Java Technology 4
try {
String url = "jdbc:msql://200.210.220.1:1114/Demo";
Connection conn = DriverManager.getConnection(url,"","");
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001");
while ( rs.next() ) {
String lastName = rs.getString("Lname");
System.out.println(lastName);
}
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
Advance Java Technology 5
Updateable Resultset
• You can update the table row using result set object. Below example
shows how to update table records.
Advance Java Technology 6
Connection con = null;
Statement st = null;
ResultSet rs = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager. getConnection(" jdbc:msql://200.210.220.1:1114/Demo " ,"user","password");
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = st.executeQuery("select accno, bal from bank");
while(rs.next()){
if(rs.getInt(1) == 100){
rs.updateDouble(2, 2000);
rs.updateRow();
System.out.println("Record updated!!!");
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} Advance Java Technology 7
ResultSetMetaData Interface
• The metadata means data about data
public int getColumnCount()throws
SQLException
it returns the total number of columns in
the ResultSet object.
public String getColumnName(int
index)throws SQLException
it returns the column name of the specified
column index.
public String getColumnTypeName(int
index)throws SQLException
it returns the column type name for the
specified index.
public String getTableName(int
index)throws SQLException
it returns the table name for the specified
column index.
Advance Java Technology 8
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system",
"oracle");
PreparedStatement ps=con.prepareStatement("select * from emp");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
con.close();
Advance Java Technology 9
Interface
• Statement
• Prepare Statement
• Callable Statement
Advance Java Technology 10
Statement
• Static sql Statement at runtime
• Can’t accept the parameter
• boolean execute (String SQL)
• Returns a boolean value of true if a ResultSet object can be retrieved
• int executeUpdate (String SQL):
• Returns the number of rows affected by the execution of the SQL statement.
• ResultSet executeQuery (String SQL):
• Returns a ResultSet object.
Advance Java Technology 11
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
Boolean ret = stmt.execute(sql);
Advance Java Technology 12
Prepare Statement
• Used sql statement many times
• Accept input parameters
Advance Java Technology 13
Connection conn = null;
PreparedStatement stmt = null;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
String sql = "UPDATE Employees set age=? WHERE id=?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, 35); // This would set age
stmt.setInt(2, 102); // This would set ID
int rows = stmt.executeUpdate();
Advance Java Technology 14
CallableStatement
• to access the database stored procedures
• can also accept runtime input parameters.
Advance Java Technology 15
DELIMITER $$
DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$
CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END $$
DELIMITER ;
Advance Java Technology 16
Connection dbConnection = null;
CallableStatement callableStatement = null;
dbConnection = getDBConnection();
callableStatement =
dbConnection.prepareCall(getDBUSERByUserIdSql);
callableStatement.setInt(1, 10);
callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR);
callableStatement.registerOutParameter(3, java.sql.Types.VARCHAR);
callableStatement.registerOutParameter(4, java.sql.Types.DATE);
callableStatement.executeUpdate();
Advance Java Technology 17
Transaction Management in JDBC
• Transaction represents a single unit of work.
• fast performance It makes the performance fast because database is hit at
the time of commit.
• The ACID properties describes the transaction management well. ACID
stands for Atomicity, Consistency, isolation and durability.
• Atomicity means either all successful or none.
• Consistency ensures bringing the database from one consistent state to
another consistent state.
• Isolation ensures that transaction is isolated from other transaction.
• Durability means once a transaction has been committed, it will remain so,
even in the event of errors, power loss etc.
Advance Java Technology 18
void setAutoCommit(boolean status) It is true bydefault means each transaction
is committed bydefault.
void commit() commits the transaction.
void rollback() cancels the transaction.
Advance Java Technology 19
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
con.commit();
con.close();
Advance Java Technology 20

More Related Content

What's hot

Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
ROHIT JAISWAR
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
Leonardo Borges
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
Christoffer Noring
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
Naveen Sagayaselvaraj
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
Mario Fusco
 
追求Jdbc on oracle最佳性能?如何才好?
追求Jdbc on oracle最佳性能?如何才好?追求Jdbc on oracle最佳性能?如何才好?
追求Jdbc on oracle最佳性能?如何才好?
maclean liu
 
Refactoring Jdbc Programming
Refactoring Jdbc ProgrammingRefactoring Jdbc Programming
Refactoring Jdbc Programmingchanwook Park
 
Testing in those hard to reach places
Testing in those hard to reach placesTesting in those hard to reach places
Testing in those hard to reach places
dn
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
Mario Fusco
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)
BoneyGawande
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Polyglot Persistence in the Real World: Cassandra + S3 + MapReduce
Polyglot Persistence in the Real World: Cassandra + S3 + MapReducePolyglot Persistence in the Real World: Cassandra + S3 + MapReduce
Polyglot Persistence in the Real World: Cassandra + S3 + MapReduce
thumbtacktech
 
Decision CAMP 2014 - Charles Forgy - Affecting rules performance
Decision CAMP 2014 - Charles Forgy - Affecting rules performanceDecision CAMP 2014 - Charles Forgy - Affecting rules performance
Decision CAMP 2014 - Charles Forgy - Affecting rules performance
Decision CAMP
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for android
Esa Firman
 
[Curso Java Basico] Aula 59: Importacao estatica (static import)
[Curso Java Basico] Aula 59: Importacao estatica (static import)[Curso Java Basico] Aula 59: Importacao estatica (static import)
[Curso Java Basico] Aula 59: Importacao estatica (static import)
Loiane Groner
 
Mobile Fest 2018. Александр Корин. Болеутоляющее
Mobile Fest 2018. Александр Корин. БолеутоляющееMobile Fest 2018. Александр Корин. Болеутоляющее
Mobile Fest 2018. Александр Корин. Болеутоляющее
MobileFest2018
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
BoneyGawande
 

What's hot (20)

Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
追求Jdbc on oracle最佳性能?如何才好?
追求Jdbc on oracle最佳性能?如何才好?追求Jdbc on oracle最佳性能?如何才好?
追求Jdbc on oracle最佳性能?如何才好?
 
Refactoring Jdbc Programming
Refactoring Jdbc ProgrammingRefactoring Jdbc Programming
Refactoring Jdbc Programming
 
Testing in those hard to reach places
Testing in those hard to reach placesTesting in those hard to reach places
Testing in those hard to reach places
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)
 
Clojure class
Clojure classClojure class
Clojure class
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Polyglot Persistence in the Real World: Cassandra + S3 + MapReduce
Polyglot Persistence in the Real World: Cassandra + S3 + MapReducePolyglot Persistence in the Real World: Cassandra + S3 + MapReduce
Polyglot Persistence in the Real World: Cassandra + S3 + MapReduce
 
Decision CAMP 2014 - Charles Forgy - Affecting rules performance
Decision CAMP 2014 - Charles Forgy - Affecting rules performanceDecision CAMP 2014 - Charles Forgy - Affecting rules performance
Decision CAMP 2014 - Charles Forgy - Affecting rules performance
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for android
 
[Curso Java Basico] Aula 59: Importacao estatica (static import)
[Curso Java Basico] Aula 59: Importacao estatica (static import)[Curso Java Basico] Aula 59: Importacao estatica (static import)
[Curso Java Basico] Aula 59: Importacao estatica (static import)
 
Mobile Fest 2018. Александр Корин. Болеутоляющее
Mobile Fest 2018. Александр Корин. БолеутоляющееMobile Fest 2018. Александр Корин. Болеутоляющее
Mobile Fest 2018. Александр Корин. Болеутоляющее
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 

Similar to Jdbc

JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
jitendral
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
Hitesh-Java
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
Swapnil Kale
 
Discuss the scrollable result set in jdbc
Discuss the scrollable result set in jdbcDiscuss the scrollable result set in jdbc
Discuss the scrollable result set in jdbc
manojmanoj218596
 
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
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
PawanMM
 
4.4 Java Database Connectivity with 5 Steps.pptx
4.4 Java Database Connectivity with 5 Steps.pptx4.4 Java Database Connectivity with 5 Steps.pptx
4.4 Java Database Connectivity with 5 Steps.pptx
Punithavel Ramani
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
hameedkhan2017
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
DEEPIKA T
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
Arturs Drozdovs
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
Zianed Hou
 

Similar to Jdbc (20)

Jdbc
JdbcJdbc
Jdbc
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
Discuss the scrollable result set in jdbc
Discuss the scrollable result set in jdbcDiscuss the scrollable result set in jdbc
Discuss the scrollable result set in jdbc
 
Batch processing Demo
Batch processing DemoBatch processing Demo
Batch processing Demo
 
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
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 
4.4 Java Database Connectivity with 5 Steps.pptx
4.4 Java Database Connectivity with 5 Steps.pptx4.4 Java Database Connectivity with 5 Steps.pptx
4.4 Java Database Connectivity with 5 Steps.pptx
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Lecture17
Lecture17Lecture17
Lecture17
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 

Recently uploaded

The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 

Recently uploaded (20)

The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 

Jdbc

  • 1. Advance Java Technology [Java Database Connectivity] Mali Nayan M Assistant Professor Department of Information Technology Sigma Institute of Engineering Advance Java Technology 1
  • 2. ResultSet interface • The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor points to before the first row. • But we can make this object to move forward and backward direction by passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well as we can make this object as updatable by: • Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSE NSITIVE, ResultSet.CONCUR_UPDATABLE); Advance Java Technology 2
  • 3. 1) public boolean next(): is used to move the cursor to the one row next from the current position. 2) public boolean previous(): is used to move the cursor to the one row previous from the current position. 3) public boolean first(): is used to move the cursor to the first row in result set object. 4) public boolean last(): is used to move the cursor to the last row in result set object. 5) public boolean absolute(int row): is used to move the cursor to the specified row number in the ResultSet object. Advance Java Technology 3
  • 4. 6) public boolean relative(int row): is used to move the cursor to the relative row number in the ResultSet object, it may be positive or negative. 7) public int getInt(int columnIndex): is used to return the data of specified column index of the current row as int. 8) public int getInt(String columnName): is used to return the data of specified column name of the current row as int. 9) public String getString(int columnIndex): is used to return the data of specified column index of the current row as String. 10) public String getString(String columnName): is used to return the data of specified column name of the current row as String. Advance Java Technology 4
  • 5. try { String url = "jdbc:msql://200.210.220.1:1114/Demo"; Connection conn = DriverManager.getConnection(url,"",""); Statement stmt = conn.createStatement(); ResultSet rs; rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001"); while ( rs.next() ) { String lastName = rs.getString("Lname"); System.out.println(lastName); } conn.close(); } catch (Exception e) { System.err.println("Got an exception! "); System.err.println(e.getMessage()); } Advance Java Technology 5
  • 6. Updateable Resultset • You can update the table row using result set object. Below example shows how to update table records. Advance Java Technology 6
  • 7. Connection con = null; Statement st = null; ResultSet rs = null; Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager. getConnection(" jdbc:msql://200.210.220.1:1114/Demo " ,"user","password"); st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = st.executeQuery("select accno, bal from bank"); while(rs.next()){ if(rs.getInt(1) == 100){ rs.updateDouble(2, 2000); rs.updateRow(); System.out.println("Record updated!!!"); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } Advance Java Technology 7
  • 8. ResultSetMetaData Interface • The metadata means data about data public int getColumnCount()throws SQLException it returns the total number of columns in the ResultSet object. public String getColumnName(int index)throws SQLException it returns the column name of the specified column index. public String getColumnTypeName(int index)throws SQLException it returns the column type name for the specified index. public String getTableName(int index)throws SQLException it returns the table name for the specified column index. Advance Java Technology 8
  • 9. Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system", "oracle"); PreparedStatement ps=con.prepareStatement("select * from emp"); ResultSet rs=ps.executeQuery(); ResultSetMetaData rsmd=rs.getMetaData(); System.out.println("Total columns: "+rsmd.getColumnCount()); System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1)); System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1)); con.close(); Advance Java Technology 9
  • 10. Interface • Statement • Prepare Statement • Callable Statement Advance Java Technology 10
  • 11. Statement • Static sql Statement at runtime • Can’t accept the parameter • boolean execute (String SQL) • Returns a boolean value of true if a ResultSet object can be retrieved • int executeUpdate (String SQL): • Returns the number of rows affected by the execution of the SQL statement. • ResultSet executeQuery (String SQL): • Returns a ResultSet object. Advance Java Technology 11
  • 12. Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL,USER,PASS); stmt = conn.createStatement(); Boolean ret = stmt.execute(sql); Advance Java Technology 12
  • 13. Prepare Statement • Used sql statement many times • Accept input parameters Advance Java Technology 13
  • 14. Connection conn = null; PreparedStatement stmt = null; Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL,USER,PASS); String sql = "UPDATE Employees set age=? WHERE id=?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, 35); // This would set age stmt.setInt(2, 102); // This would set ID int rows = stmt.executeUpdate(); Advance Java Technology 14
  • 15. CallableStatement • to access the database stored procedures • can also accept runtime input parameters. Advance Java Technology 15
  • 16. DELIMITER $$ DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$ CREATE PROCEDURE `EMP`.`getEmpName` (IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255)) BEGIN SELECT first INTO EMP_FIRST FROM Employees WHERE ID = EMP_ID; END $$ DELIMITER ; Advance Java Technology 16
  • 17. Connection dbConnection = null; CallableStatement callableStatement = null; dbConnection = getDBConnection(); callableStatement = dbConnection.prepareCall(getDBUSERByUserIdSql); callableStatement.setInt(1, 10); callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR); callableStatement.registerOutParameter(3, java.sql.Types.VARCHAR); callableStatement.registerOutParameter(4, java.sql.Types.DATE); callableStatement.executeUpdate(); Advance Java Technology 17
  • 18. Transaction Management in JDBC • Transaction represents a single unit of work. • fast performance It makes the performance fast because database is hit at the time of commit. • The ACID properties describes the transaction management well. ACID stands for Atomicity, Consistency, isolation and durability. • Atomicity means either all successful or none. • Consistency ensures bringing the database from one consistent state to another consistent state. • Isolation ensures that transaction is isolated from other transaction. • Durability means once a transaction has been committed, it will remain so, even in the event of errors, power loss etc. Advance Java Technology 18
  • 19. void setAutoCommit(boolean status) It is true bydefault means each transaction is committed bydefault. void commit() commits the transaction. void rollback() cancels the transaction. Advance Java Technology 19
  • 20. Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); con.setAutoCommit(false); Statement stmt=con.createStatement(); stmt.executeUpdate("insert into user420 values(190,'abhi',40000)"); stmt.executeUpdate("insert into user420 values(191,'umesh',50000)"); con.commit(); con.close(); Advance Java Technology 20