SlideShare a Scribd company logo
JDBCJava Database Connectivity
Core Concepts
www.sunilos.com
www.raystec.com
www.SunilOS.com 2
Connect with Database
Steps to make a database call:
1. Load Driver
2. Create connection
3. Create statement
4. Execute query and get ResultSet or execute
insert/update/delete query and get number of records affected
Note : Driver jar must be in classpath
www.SunilOS.com 3
MYSQL – Get Data
public static void main(String args[]) throws Exception{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root",“pass");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, color FROM part");
System.out.println("IDtNametColor");
while (rs.next()) {
System.out.print(rs.getString(1));
System.out.print("t" + rs.getString(2));
System.out.println("t" + rs.getString("color"));
}
stmt.close();
conn.close();
}
Load Driver
DB URL Login PWD
SQL
Column value by index
Column value by name
www.SunilOS.com 4
MYSQL – Insert/Update Data
Class.forName("com.mysql.jdbc.Driver");//load Driver
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost/testdb", "root", “pass");
//make connection
Statement stmt = conn.createStatement(); //create statement
//execute query
int i= stmt.executeUpdate(“INSERT into part values (4,'plat','Green',1)"); /
System.out.print( i + “ Record(s) Updated ”);
//close statements
stmt.close(); conn.close();
www.SunilOS.com 5
Prepared Statement
Statement stmt = conn.createStatement();
String sql =“INSERT into part values (4,'plat','Green',1)“;
int i= stmt.executeUpdate(sql);
OR
int id = 4; String name =“plat”; String color = “Green”, int unitId=1;
String sql = “INSERT into part values (“+ id +” , ‘ “ + name + ” ’ ,‘ “+color + ” ’,“+ unitId +”)”;
int i= stmt.executeUpdate(sql);
OR
int id = 4; String name =“plat”; String color = “Green”, int unitId=1;
PreparedStatement ps = conn.prepareStatement(“INSERT into part values (?,?,?,?)")
ps.setInt(1,id);
ps.setString(2,name);
ps.setString(3,color);
ps.setInt(4,unitId);
int i = ps.executeUpdate();
www.SunilOS.com 6
Mapping Java Types to SQL Types
SQL type Java Type
CHAR, VARCHAR, LONGVARCHAR String
NUMERIC, DECIMAL java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT, DOUBLE double
BINARY, VARBINARY, LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
Date + Time
(Nano sec)
www.SunilOS.com 7
Database Time
Java defines three classes to handle date and time:
 java.sql.Date
o year, month, day
 java.sql.Time
o hours, minutes, seconds
 java.sql.Timestamp
o year, month, day, hours, minutes, seconds, nanoseconds
o By default Timestamp should be used
www.SunilOS.com 8
Other Databases
 MS SQL
String driver = “com.microsoft.sqlserver.jdbc.SQLServerDriver”;
String url = “jdbc:sqlserver://localhostsqlexpress;user=sa;password=secret”;
Class.forName(driver);
Connection conn = DriverManager.getConnection(url);
 ORACLE
String driver = “oracle.jdbc.OracleDriver”;
String url = “jdbc:oracle://localhost/orcl”;
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,“scott", “tiger");
www.SunilOS.com 9
Javabean
public class Marksheet {
private String rollNo = null;
private String name = null;
private int chemistry = 0;
private int physics = 0;
private int maths = 0;
public Marksheet(){}//Def
Constructor
public String getRollNO() {
return rollNo ;
}
public void setRollN(String
rollNo) {
this.rollNo = rollNo ;
}
..Other Setter/Getter
Marksheet
-rollNo : String
-name : String
-chemistry : int
-physics : int
-maths:int
+setters
+getters
www.SunilOS.com 10
Data Access Object
MarksheetDAO
+ add (Marksheet)
+ update (Marksheet)
+ delete (rollNo) : Marksheet
+ get (rollNo) : Marksheet
+getMeritList(): ArrayList
+search(Marksheet)
TestMarksheetDAO
+ testAdd ()
+ testUpdate ()
+ testDelete ()
+ testGet ()
+testGetMeritList()
+testSearch()
+main(String[])
Disclaimer
This is an educational presentation to enhance the skill
of computer science students.
This presentation is available for free to computer
science students.
Some internet images from different URLs are used in
this presentation to simplify technical examples and
correlate examples with the real world.
We are grateful to owners of these URLs and pictures.
www.SunilOS.com 11
Thank You!
www.SunilOS.com 12
www.SunilOS.com

More Related Content

What's hot

DCN Practical
DCN PracticalDCN Practical
DCN Practical
Niraj Bharambe
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
Niraj Bharambe
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
Hermann Hueck
 
#5 (Remote Method Invocation)
#5 (Remote Method Invocation)#5 (Remote Method Invocation)
#5 (Remote Method Invocation)
Ghadeer AlHasan
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
Stéphane Wirtel
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of Abstraction
Alex Miller
 
Unit Testing with Foq
Unit Testing with FoqUnit Testing with Foq
Unit Testing with Foq
Phillip Trelford
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwo
Eishay Smith
 
The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184
Mahmoud Samir Fayed
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
Sunil OS
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
Technopark
 
The Ring programming language version 1.5.3 book - Part 26 of 184
The Ring programming language version 1.5.3 book - Part 26 of 184The Ring programming language version 1.5.3 book - Part 26 of 184
The Ring programming language version 1.5.3 book - Part 26 of 184
Mahmoud Samir Fayed
 
Clojure class
Clojure classClojure class
Clojure class
Aysylu Greenberg
 
JDK 8
JDK 8JDK 8
Cheat sheet python3
Cheat sheet python3Cheat sheet python3
Cheat sheet python3
sxw2k
 
Into Clojure
Into ClojureInto Clojure
Into Clojure
Alf Kristian Støyle
 
はじめてのGroovy
はじめてのGroovyはじめてのGroovy
はじめてのGroovy
Tsuyoshi Yamamoto
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
Svetlin Nakov
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲーム
Noritada Shimizu
 

What's hot (19)

DCN Practical
DCN PracticalDCN Practical
DCN Practical
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 
#5 (Remote Method Invocation)
#5 (Remote Method Invocation)#5 (Remote Method Invocation)
#5 (Remote Method Invocation)
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of Abstraction
 
Unit Testing with Foq
Unit Testing with FoqUnit Testing with Foq
Unit Testing with Foq
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwo
 
The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
 
The Ring programming language version 1.5.3 book - Part 26 of 184
The Ring programming language version 1.5.3 book - Part 26 of 184The Ring programming language version 1.5.3 book - Part 26 of 184
The Ring programming language version 1.5.3 book - Part 26 of 184
 
Clojure class
Clojure classClojure class
Clojure class
 
JDK 8
JDK 8JDK 8
JDK 8
 
Cheat sheet python3
Cheat sheet python3Cheat sheet python3
Cheat sheet python3
 
Into Clojure
Into ClojureInto Clojure
Into Clojure
 
はじめてのGroovy
はじめてのGroovyはじめてのGroovy
はじめてのGroovy
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲーム
 

Similar to JDBC Core Concept

Jdbc
JdbcJdbc
Jdbc
lathasiva
 
Lecture17
Lecture17Lecture17
Lecture17
vantinhkhuc
 
JDBC
JDBCJDBC
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
Waheedullah Suliman Khail
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
sandeep54552
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
Arturs Drozdovs
 
Java JDBC
Java JDBCJava JDBC
Jdbc
JdbcJdbc
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
Hitesh-Java
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
22jdbc
22jdbc22jdbc
22jdbc
Adil Jafri
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
Eleonora Ciceri
 
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
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
Atul Saurabh
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
Zianed Hou
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
Fulvio Corno
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
Dharma Kshetri
 
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
 
Jdbc
JdbcJdbc
Jdbc
Indu Lata
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
Swapnil Kale
 

Similar to JDBC Core Concept (20)

Jdbc
JdbcJdbc
Jdbc
 
Lecture17
Lecture17Lecture17
Lecture17
 
JDBC
JDBCJDBC
JDBC
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
22jdbc
22jdbc22jdbc
22jdbc
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
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
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
 
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
JdbcJdbc
Jdbc
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 

Recently uploaded

S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Assessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptxAssessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptx
Kavitha Krishnan
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 

Recently uploaded (20)

S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Assessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptxAssessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptx
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 

JDBC Core Concept

  • 1. JDBCJava Database Connectivity Core Concepts www.sunilos.com www.raystec.com
  • 2. www.SunilOS.com 2 Connect with Database Steps to make a database call: 1. Load Driver 2. Create connection 3. Create statement 4. Execute query and get ResultSet or execute insert/update/delete query and get number of records affected Note : Driver jar must be in classpath
  • 3. www.SunilOS.com 3 MYSQL – Get Data public static void main(String args[]) throws Exception{ Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root",“pass"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id, name, color FROM part"); System.out.println("IDtNametColor"); while (rs.next()) { System.out.print(rs.getString(1)); System.out.print("t" + rs.getString(2)); System.out.println("t" + rs.getString("color")); } stmt.close(); conn.close(); } Load Driver DB URL Login PWD SQL Column value by index Column value by name
  • 4. www.SunilOS.com 4 MYSQL – Insert/Update Data Class.forName("com.mysql.jdbc.Driver");//load Driver Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost/testdb", "root", “pass"); //make connection Statement stmt = conn.createStatement(); //create statement //execute query int i= stmt.executeUpdate(“INSERT into part values (4,'plat','Green',1)"); / System.out.print( i + “ Record(s) Updated ”); //close statements stmt.close(); conn.close();
  • 5. www.SunilOS.com 5 Prepared Statement Statement stmt = conn.createStatement(); String sql =“INSERT into part values (4,'plat','Green',1)“; int i= stmt.executeUpdate(sql); OR int id = 4; String name =“plat”; String color = “Green”, int unitId=1; String sql = “INSERT into part values (“+ id +” , ‘ “ + name + ” ’ ,‘ “+color + ” ’,“+ unitId +”)”; int i= stmt.executeUpdate(sql); OR int id = 4; String name =“plat”; String color = “Green”, int unitId=1; PreparedStatement ps = conn.prepareStatement(“INSERT into part values (?,?,?,?)") ps.setInt(1,id); ps.setString(2,name); ps.setString(3,color); ps.setInt(4,unitId); int i = ps.executeUpdate();
  • 6. www.SunilOS.com 6 Mapping Java Types to SQL Types SQL type Java Type CHAR, VARCHAR, LONGVARCHAR String NUMERIC, DECIMAL java.math.BigDecimal BIT boolean TINYINT byte SMALLINT short INTEGER int BIGINT long REAL float FLOAT, DOUBLE double BINARY, VARBINARY, LONGVARBINARY byte[] DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp Date + Time (Nano sec)
  • 7. www.SunilOS.com 7 Database Time Java defines three classes to handle date and time:  java.sql.Date o year, month, day  java.sql.Time o hours, minutes, seconds  java.sql.Timestamp o year, month, day, hours, minutes, seconds, nanoseconds o By default Timestamp should be used
  • 8. www.SunilOS.com 8 Other Databases  MS SQL String driver = “com.microsoft.sqlserver.jdbc.SQLServerDriver”; String url = “jdbc:sqlserver://localhostsqlexpress;user=sa;password=secret”; Class.forName(driver); Connection conn = DriverManager.getConnection(url);  ORACLE String driver = “oracle.jdbc.OracleDriver”; String url = “jdbc:oracle://localhost/orcl”; Class.forName(driver); Connection conn = DriverManager.getConnection(url,“scott", “tiger");
  • 9. www.SunilOS.com 9 Javabean public class Marksheet { private String rollNo = null; private String name = null; private int chemistry = 0; private int physics = 0; private int maths = 0; public Marksheet(){}//Def Constructor public String getRollNO() { return rollNo ; } public void setRollN(String rollNo) { this.rollNo = rollNo ; } ..Other Setter/Getter Marksheet -rollNo : String -name : String -chemistry : int -physics : int -maths:int +setters +getters
  • 10. www.SunilOS.com 10 Data Access Object MarksheetDAO + add (Marksheet) + update (Marksheet) + delete (rollNo) : Marksheet + get (rollNo) : Marksheet +getMeritList(): ArrayList +search(Marksheet) TestMarksheetDAO + testAdd () + testUpdate () + testDelete () + testGet () +testGetMeritList() +testSearch() +main(String[])
  • 11. Disclaimer This is an educational presentation to enhance the skill of computer science students. This presentation is available for free to computer science students. Some internet images from different URLs are used in this presentation to simplify technical examples and correlate examples with the real world. We are grateful to owners of these URLs and pictures. www.SunilOS.com 11

Editor's Notes

  1. www.sunilos.com
  2. Cell- 98273 60504
  3. Cell- 98273 60504
  4. Cell- 98273 60504
  5. Cell- 98273 60504
  6. Cell- 98273 60504
  7. Cell- 98273 60504
  8. Cell- 98273 60504
  9. Cell- 98273 60504
  10. Cell- 98273 60504