SlideShare a Scribd company logo
JDBC
CS 124
JDBC
 Java Database Connectivity
 Database Access Interface
 provides access to a relational database (by
allowing SQL statements to be sent and executed
through a Java program)
 JDBC package: set of Java classes that facilitate
this access (java.sql.*)
 Comes with JDK (since 1.1)
JDBC Driver
Need a driver, specific to the DB product, to
mediate between JDBC and the database
 the driver is a Java class that needs to be loaded
first
Relational
DBMS
Java Program
- load driver
- establish connection
- send SQL statements
JDBC-ODBC Bridge
 Driver that interfaces with ODBC (Object
Database Connectivity--also an access
interface)
 Easiest way to access databases created by
Microsoft products
 register database as an ODBC data source
 use JDBC-ODBC bridge as the JDBC driver
(included in JDK distribution)
Key Classes in JDBC
 Connection
 need to create an instance of this class when
establishing a connection to the database
 Statement
 for issuing SQL statements
 ResultSet (interface)
 a ResultSet object represents the table returned
by an SQL select statement
Establishing a Connection
Use the getConnection() method
 under the DriverManager class
 String argument: "jdbc:driver:name”
 returns a Connection object
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
// above line loads the jdbc-odbc driver
String dbname = “jdbc:odbc:MyDB”;
Connection c = DriverManager.getConnection(dbname);
Creating a
Statement Object
Execute the createStatement() method on the
Connection object
 returns a Statement object
 afterwards, run methods on the Statement object
to execute an SQL statement
Statement s = c.createStatement();
Methods of the
Statement Class
 Methods of the Statement class require a string
parameter containing the SQL statement
 executeQuery()
 requires a String argument (a SELECT statement)
 returns a ResultSet object representing the table returned
 executeUpdate()
 requires a String argument
(an INSERT, UPDATE, or DELETE statement)
 returns an int (row count, in most cases)
The ResultSet Interface
 A ResultSet object represents the table
returned by the select statement sent
 Navigation/retrieval methods
 next(): moves to the next row (first row if called
for the first time), returns false if no rows remain
 getXXX() methods return the value of a field for
the current row
ResulSet example
ResultSet rs;
rs = s.executeQuery(“SELECT * FROM [ORDER]”);
rs.next(); // gets the first row (use in a loop for multiple rows)
// suppose the ORDER table has an integer field
// called quantity
int myvar = rs.getInt(“quantity”);
// if you knew that quantity is the 2nd field in the table
myvar = rs.getInt(2);
Need braces because
ORDER is a reserved
word in SQL
Exercise
 Create a Microsoft Access table
 insert sample rows
 Add an ODBC data source
 use the Microsoft Access driver
 associate with the created database
 Create a Java program
 use JDBC-ODBC bridge
 create a loop that lists all rows of the table
executeQuery( ) example
…
Statement s = con.createStatement();
ResultSet rs = s.executeQuery(
“SELECT * FROM STUDENT WHERE QPI > 3.0”
);
while ( rs.next() )
{
String name = rs.getString(“LastName”);
int y = rs.getInt(“Year”);
double qpi = rs.getDouble(“QPI”);
System.out.println( name + “ ” + y + “ ” + qpi);
}
executeUpdate( ) example
…
Statement s = con.createStatement();
int result;
result = s.executeUpdate(
“DELETE FROM EMPLOYEE WHERE DeptCode=‘CS’”
);
System.out.println( result + “ rows deleted.” );
The PreparedStatement class
 PreparedStatement: a Statement that
specifies parameters through Java code
 The SQL statements take different forms
when you specify different parameter values
 Useful when query is performed repeatedly
 Formatting of literal values is easier
Version 1 (Statement)
// suppose lastName is a String variable
Statement s = con.createStatement();
ResultSet rs = s.executeQuery(
“SELECT * FROM STUDENT WHERE LastName = ‘” + lastName +”’”
);
while ( rs.next() )
{
String name =
rs.getString(“LastName”) + rs.getString(“FirstName”);
int y = rs.getInt(“Year”);
double qpi = rs.getDouble(“QPI”);
System.out.println( name + “ ” + y + “ ” + qpi);
}
Query string is built manually
Version 2 (PreparedStatement)
// suppose lastName is a String variable
PreparedStatement s = con.prepareStatement(
“SELECT * FROM STUDENT WHERE LastName = ?”
);
s.setString( 1, lastName );
ResultSet rs = s.executeQuery();
while ( rs.next() )
{
String name =
rs.getString(“LastName”) + rs.getString(“FirstName”);
int y = rs.getInt(“Year”);
double qpi = rs.getDouble(“QPI”);
System.out.println( name + “ ” + y + “ ” + qpi);
}
the appropriate literal
is “inserted” in the query
Summary
 JDBC allows you to write Java programs that
manipulate a database
 A driver (often a separate product) is required
that facilitates access
 Key classes: Connection, Statement,
PreparedStatement, and ResultSet
 Other features: metadata and stored-proc
invocation

More Related Content

PPT
Executing Sql Commands
phanleson
 
PPT
Executing Sql Commands
leminhvuong
 
PDF
Java 1-contd
Mukesh Tekwani
 
PDF
Lecture17
vantinhkhuc
 
PPT
JDBC Tutorial
Information Technology
 
PPT
3 database-jdbc(1)
hameedkhan2017
 
PPT
JDBC – Java Database Connectivity
Information Technology
 
PDF
spring-tutorial
Arjun Shanka
 
Executing Sql Commands
phanleson
 
Executing Sql Commands
leminhvuong
 
Java 1-contd
Mukesh Tekwani
 
Lecture17
vantinhkhuc
 
JDBC Tutorial
Information Technology
 
3 database-jdbc(1)
hameedkhan2017
 
JDBC – Java Database Connectivity
Information Technology
 
spring-tutorial
Arjun Shanka
 

Similar to CS124-L9-JDBC.ppt Add more information to your upload (20)

PPT
Jdbc
smvdurajesh
 
PPTX
Jdbc
Indu Lata
 
PDF
Jdbc[1]
Fulvio Corno
 
PDF
JDBC programming
Fulvio Corno
 
PPT
jdbc_presentation.ppt
DrMeenakshiS
 
PDF
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
PPTX
Jdbc ja
DEEPIKA T
 
PPT
JDBC for CSQL Database
jitendral
 
PPTX
JDBC
Balwinder Kumar
 
PPS
Jdbc api
kamal kotecha
 
DOCX
Android sq lite-chapter 22
Dr. Ramkumar Lakshminarayanan
 
PPTX
Java Databse Connectvity- Alex Jose
Dipayan Sarkar
 
PPT
jdbc
vikram singh
 
PPT
Jdbc
lathasiva
 
PPT
JDBC.ppt JDBC_FM_2012_201JDBC_FM_2012_201
rorebik626
 
PPT
JDBC_Template for database connection using Spring
gangishettysaikrishn
 
PPT
30 5 Database Jdbc
phanleson
 
PPT
JDBC Connecticity.ppt
Swapnil Kale
 
PPT
Spsl v unit - final
Sasidhar Kothuru
 
PPT
Spsl vi unit final
Sasidhar Kothuru
 
Jdbc
Indu Lata
 
Jdbc[1]
Fulvio Corno
 
JDBC programming
Fulvio Corno
 
jdbc_presentation.ppt
DrMeenakshiS
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Jdbc ja
DEEPIKA T
 
JDBC for CSQL Database
jitendral
 
Jdbc api
kamal kotecha
 
Android sq lite-chapter 22
Dr. Ramkumar Lakshminarayanan
 
Java Databse Connectvity- Alex Jose
Dipayan Sarkar
 
Jdbc
lathasiva
 
JDBC.ppt JDBC_FM_2012_201JDBC_FM_2012_201
rorebik626
 
JDBC_Template for database connection using Spring
gangishettysaikrishn
 
30 5 Database Jdbc
phanleson
 
JDBC Connecticity.ppt
Swapnil Kale
 
Spsl v unit - final
Sasidhar Kothuru
 
Spsl vi unit final
Sasidhar Kothuru
 
Ad

Recently uploaded (20)

PPTX
Basics of Memristors from zero to hero.pptx
onterusmail
 
PPTX
22. PSYCHOTOGENIC DRUGS.pptx 60d7co Gurinder
sriramraja650
 
PPTX
2.Important-Definihhhhhhtions18 (1).pptx
trishalasharma7
 
PPTX
Boolean Algebra-Properties and Theorems.pptx
bhavanavarri5458
 
PPTX
Normal distriutionvggggggggggggggggggg.pptx
JayeshTaneja4
 
PPTX
great itemsgreat itemsgreat itemsgreat items.pptx
saurabh13smr
 
PPT
3 01032017tyuiryhjrhyureyhjkfdhghfrugjhf
DharaniMani4
 
PPT
Susunan & Bagian DRAWING 153UWYHSGDGH.ppt
RezaFbriadi
 
PDF
INTEL CPU 3RD GEN.pdf variadas de computacion
juancardozzo26
 
PPTX
西班牙海牙认证瓦伦西亚国际大学毕业证与成绩单文凭复刻快速办理毕业证书
sw6vvn9s
 
PPTX
G6Q1 WEEK 2 SCIENCE PPT.pptxLVLLLLLLLLLLLLLLLLL
DitaSIdnay
 
PPTX
PHISHING ATTACKS. _. _.pptx[]
kumarrana7525
 
PPTX
PPT on the topic of programming language
dishasindhava
 
PPTX
Aryanbarot28.pptx Introduction of window os for the projects
aryanbarot004
 
PPTX
Intro_S4HANA_Using_Global_Bike_Slides_SD_en_v4.1.pptx
trishalasharma7
 
PPTX
Query and optimizing operating system.pptx
YoomifTube
 
PDF
Portable Veterinary Ultrasound Scanners & Animal Medical Equipment - TcCryo
3447752272
 
PPTX
Basics of Memristors and fundamentals.pptx
onterusmail
 
PPT
community diagnosis slides show health. ppt
michaelbrucebwana
 
PDF
Abbreviations in NC-ISM_syllabus.pdf hejsnsjs
raipureastha08
 
Basics of Memristors from zero to hero.pptx
onterusmail
 
22. PSYCHOTOGENIC DRUGS.pptx 60d7co Gurinder
sriramraja650
 
2.Important-Definihhhhhhtions18 (1).pptx
trishalasharma7
 
Boolean Algebra-Properties and Theorems.pptx
bhavanavarri5458
 
Normal distriutionvggggggggggggggggggg.pptx
JayeshTaneja4
 
great itemsgreat itemsgreat itemsgreat items.pptx
saurabh13smr
 
3 01032017tyuiryhjrhyureyhjkfdhghfrugjhf
DharaniMani4
 
Susunan & Bagian DRAWING 153UWYHSGDGH.ppt
RezaFbriadi
 
INTEL CPU 3RD GEN.pdf variadas de computacion
juancardozzo26
 
西班牙海牙认证瓦伦西亚国际大学毕业证与成绩单文凭复刻快速办理毕业证书
sw6vvn9s
 
G6Q1 WEEK 2 SCIENCE PPT.pptxLVLLLLLLLLLLLLLLLLL
DitaSIdnay
 
PHISHING ATTACKS. _. _.pptx[]
kumarrana7525
 
PPT on the topic of programming language
dishasindhava
 
Aryanbarot28.pptx Introduction of window os for the projects
aryanbarot004
 
Intro_S4HANA_Using_Global_Bike_Slides_SD_en_v4.1.pptx
trishalasharma7
 
Query and optimizing operating system.pptx
YoomifTube
 
Portable Veterinary Ultrasound Scanners & Animal Medical Equipment - TcCryo
3447752272
 
Basics of Memristors and fundamentals.pptx
onterusmail
 
community diagnosis slides show health. ppt
michaelbrucebwana
 
Abbreviations in NC-ISM_syllabus.pdf hejsnsjs
raipureastha08
 
Ad

CS124-L9-JDBC.ppt Add more information to your upload

  • 2. JDBC  Java Database Connectivity  Database Access Interface  provides access to a relational database (by allowing SQL statements to be sent and executed through a Java program)  JDBC package: set of Java classes that facilitate this access (java.sql.*)  Comes with JDK (since 1.1)
  • 3. JDBC Driver Need a driver, specific to the DB product, to mediate between JDBC and the database  the driver is a Java class that needs to be loaded first Relational DBMS Java Program - load driver - establish connection - send SQL statements
  • 4. JDBC-ODBC Bridge  Driver that interfaces with ODBC (Object Database Connectivity--also an access interface)  Easiest way to access databases created by Microsoft products  register database as an ODBC data source  use JDBC-ODBC bridge as the JDBC driver (included in JDK distribution)
  • 5. Key Classes in JDBC  Connection  need to create an instance of this class when establishing a connection to the database  Statement  for issuing SQL statements  ResultSet (interface)  a ResultSet object represents the table returned by an SQL select statement
  • 6. Establishing a Connection Use the getConnection() method  under the DriverManager class  String argument: "jdbc:driver:name”  returns a Connection object Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); // above line loads the jdbc-odbc driver String dbname = “jdbc:odbc:MyDB”; Connection c = DriverManager.getConnection(dbname);
  • 7. Creating a Statement Object Execute the createStatement() method on the Connection object  returns a Statement object  afterwards, run methods on the Statement object to execute an SQL statement Statement s = c.createStatement();
  • 8. Methods of the Statement Class  Methods of the Statement class require a string parameter containing the SQL statement  executeQuery()  requires a String argument (a SELECT statement)  returns a ResultSet object representing the table returned  executeUpdate()  requires a String argument (an INSERT, UPDATE, or DELETE statement)  returns an int (row count, in most cases)
  • 9. The ResultSet Interface  A ResultSet object represents the table returned by the select statement sent  Navigation/retrieval methods  next(): moves to the next row (first row if called for the first time), returns false if no rows remain  getXXX() methods return the value of a field for the current row
  • 10. ResulSet example ResultSet rs; rs = s.executeQuery(“SELECT * FROM [ORDER]”); rs.next(); // gets the first row (use in a loop for multiple rows) // suppose the ORDER table has an integer field // called quantity int myvar = rs.getInt(“quantity”); // if you knew that quantity is the 2nd field in the table myvar = rs.getInt(2); Need braces because ORDER is a reserved word in SQL
  • 11. Exercise  Create a Microsoft Access table  insert sample rows  Add an ODBC data source  use the Microsoft Access driver  associate with the created database  Create a Java program  use JDBC-ODBC bridge  create a loop that lists all rows of the table
  • 12. executeQuery( ) example … Statement s = con.createStatement(); ResultSet rs = s.executeQuery( “SELECT * FROM STUDENT WHERE QPI > 3.0” ); while ( rs.next() ) { String name = rs.getString(“LastName”); int y = rs.getInt(“Year”); double qpi = rs.getDouble(“QPI”); System.out.println( name + “ ” + y + “ ” + qpi); }
  • 13. executeUpdate( ) example … Statement s = con.createStatement(); int result; result = s.executeUpdate( “DELETE FROM EMPLOYEE WHERE DeptCode=‘CS’” ); System.out.println( result + “ rows deleted.” );
  • 14. The PreparedStatement class  PreparedStatement: a Statement that specifies parameters through Java code  The SQL statements take different forms when you specify different parameter values  Useful when query is performed repeatedly  Formatting of literal values is easier
  • 15. Version 1 (Statement) // suppose lastName is a String variable Statement s = con.createStatement(); ResultSet rs = s.executeQuery( “SELECT * FROM STUDENT WHERE LastName = ‘” + lastName +”’” ); while ( rs.next() ) { String name = rs.getString(“LastName”) + rs.getString(“FirstName”); int y = rs.getInt(“Year”); double qpi = rs.getDouble(“QPI”); System.out.println( name + “ ” + y + “ ” + qpi); } Query string is built manually
  • 16. Version 2 (PreparedStatement) // suppose lastName is a String variable PreparedStatement s = con.prepareStatement( “SELECT * FROM STUDENT WHERE LastName = ?” ); s.setString( 1, lastName ); ResultSet rs = s.executeQuery(); while ( rs.next() ) { String name = rs.getString(“LastName”) + rs.getString(“FirstName”); int y = rs.getInt(“Year”); double qpi = rs.getDouble(“QPI”); System.out.println( name + “ ” + y + “ ” + qpi); } the appropriate literal is “inserted” in the query
  • 17. Summary  JDBC allows you to write Java programs that manipulate a database  A driver (often a separate product) is required that facilitates access  Key classes: Connection, Statement, PreparedStatement, and ResultSet  Other features: metadata and stored-proc invocation