SlideShare une entreprise Scribd logo
1  sur  13
Télécharger pour lire hors ligne
JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to
connect and execute the query with the database. It is a part of Java SE
(Java Standard Edition). JDBC API uses JDBC drivers to connect with
the database. The JDBC library includes APIs for each of the tasks
mentioned below that are commonly associated with database usage.
• Making a connection to a database.
• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & Modifying the resulting records.
Applications of JDBC
Fundamentally, JDBC is a specification that provides a complete set of
interfaces that allows for portable access to an underlying database.
Java can be used to write different types of executables, such as −
• Java Applications
• Java Applets
• Java Servlets
• Java ServerPages (JSPs)
• Enterprise JavaBeans (EJBs).
All of these different executable are able to use a JDBC driver to access
a database, and take advantage of the stored data.
We can use JDBC API to access tabular data stored in any
relational database. By the help of JDBC API, we can save, update,
delete and fetch data from the database. It is like Open Database
Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st
September, 2017. It is based on the X/Open SQL Call Level Interface.
The java.sql package contains classes and interfaces for JDBC API. A
list of popular interfaces of JDBC API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
A list of popular classes of JDBC API is given below:
o DriverManager class
o Types class
There are four types of JDBC drivers:
o JDBC-ODBC Bridge Driver,
o Native Driver,
o Network Protocol Driver, and
o Thin Driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function
calls.
This is now discouraged because of thin driver.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle
recommends that you use JDBC drivers provided by the vendor of your
database instead of the JDBC-ODBC Bridge.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into
the ODBC function calls.
o The ODBC driver needs to be installed on the client machine.
Topic: Establishing Connectivity
There are 5 steps to connect any java application with the database using
JDBC. These steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class.
This method is used to dynamically load the driver class.
Syntax of forName() method
1. public static void forName(String className)throws ClassNotFoundE
xception
Example to register the OracleDriver class
Here, Java program is loading oracle driver to establish database connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish
Connection with the database.
Syntax of getConnection() method
public static Connection getConnection(String url)throws SQLExceptio
n
public static Connection getConnection(String url,String username,String p
assword) throws
SQLException
Example to establish connection with the Oracle
database
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:
1521:xe","system","system");
1. Driver class: The driver class for the oracle database
is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database,
thin is the driver, localhost is the server name on which oracle is running, we may also
use IP address, 1521 is the port number and XE is the Oracle service name.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle
database.
3) Create the Statement object
The createStatement() method of Connection Interface is used to create statement.
The object of statement is responsible to execute queries with the database.
Syntax of createStatement() method
1. public Statement createStatement() throws SQLException
Example to create the statement object
1. Statement stmt=con.createStatement();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries
to the database.This method returns the object of ResultSet that can be
used to get all the records of a table.
Syntax of executeQuery() method
1. public ResultSet executeQuery(String sql) throws SQLException
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically
The close() method of Connection interface is used to close the connection.
Syntax of close() method
public void close() throws SQLException
Example to close connection
con.close();
Creating and Executing SQL statement
Executing SQL on the Connection involves two further objects:
• we create a Statement object, to which we pass the SQL to be
executed and set any required options;
• we read the result of the query via a ResultSet object.
Creating a Statement object is simple once we have our Connection:
Connection con =DriverManager.getConnection();
Statement stmt = con.createStatement();
Then, to execute a simple SQL statement and get the corresponding
result, we write something as follows:
int id = ... get ID from somewhere ...
String sql = "SELECT Name FROM Users WHERE Id = " + id;
ResultSet rs = st.executeQuery(sql);
// ... read from result set ...
The executeQuery() method returns a ResultSet object from
which the result data can be read. For a simple SELECT query
such as this, we would always expect a result set to be returned,
which would be empty if no rows were returned.
The ResultSet object returned can then be queried to pull out the
rows and colums of the result.
Working With ResultSet Object
Having obtained a database connection and executed a query via
a Statement object, the next stage is to pull out the data from the ResultSet. A
result set consists of zero or more rows. Let's suppose that our query on
a User’s table returns rows in the following format:
Id
(INT)
UserName
(VARCHAR)
FirstName
(VARCHAR)
Surname
(VARCHAR)
TimeRegistered
(TIMESTAMP)
3 dsmith David Smith 2008-04-02 18:16:22
4 ntroberts Nigel Roberts 2008-05-01 20:11:01
6 bgsmithers Bill Smithers 2008-05-02 02:43:52
Now we can pull out the details of successive users from the result as follows:
ResultSet rs = st.getResultSet();
try {
while (rs.next()) {
int id = rs.getInt(1);
String userName = rs.getString(2);
String firstName = rs.getString(3);
String surname = rs.getString(4);
Timestamp timeReg = rs.getTimestamp(5);
// ... do something with these variables ...
}
}
finally {
con.close();
}
Notice the repeated call to next(), which returns true if there is another row of
data, and at the same time gets the ResultSet ready to start reading data from
that next row.
The code above illustrates the following points and topics:
• Column numbers start at 1, not zero.
• There are mappings between SQL and Java data types. For example, a
SQL INT is mapped to a Java int; SQL VARCHARs are mapped to
Java Strings. We call a get() method on the ResultSet that is appropriate to
the type we want to retrieve. (As discussed on the next page, it turns out that
these methods luckily can often perform conversion if we don't choose the
exact type.)
• The ResultSet and/or Statement needs to be closed. Whilst in emergencies
they will be closed on finalization, it's preferable to close them explicitly as
soon as they are no longer needed. Unfortunately, there are three different
types of JDBC resource, all of which have a close() method! In a moment,
we'll discuss when to close JDBC resources.
Jdbc
Jdbc

Contenu connexe

Tendances (19)

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 sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
Database programming
Database programmingDatabase programming
Database programming
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
JDBC
JDBCJDBC
JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc connectivity in java
Jdbc connectivity in javaJdbc connectivity in java
Jdbc connectivity in java
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
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 1
Jdbc 1Jdbc 1
Jdbc 1
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
Jdbc   Jdbc
Jdbc
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
 
Sql interview-book
Sql interview-bookSql interview-book
Sql interview-book
 
Database connect
Database connectDatabase connect
Database connect
 

Similaire à Jdbc (20)

JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
JDBC
JDBCJDBC
JDBC
 
Prashanthi
PrashanthiPrashanthi
Prashanthi
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)
 
Lecture17
Lecture17Lecture17
Lecture17
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
Advance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-databaseAdvance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-database
 

Dernier

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 

Dernier (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Jdbc

  • 1. JDBC JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database. It is a part of Java SE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database. The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage. • Making a connection to a database. • Creating SQL or MySQL statements. • Executing SQL or MySQL queries in the database. • Viewing & Modifying the resulting records. Applications of JDBC Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as − • Java Applications • Java Applets • Java Servlets • Java ServerPages (JSPs) • Enterprise JavaBeans (EJBs). All of these different executable are able to use a JDBC driver to access a database, and take advantage of the stored data. We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API, we can save, update, delete and fetch data from the database. It is like Open Database Connectivity (ODBC) provided by Microsoft.
  • 2. The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces for JDBC API. A list of popular interfaces of JDBC API are given below: o Driver interface o Connection interface o Statement interface o PreparedStatement interface o CallableStatement interface o ResultSet interface o ResultSetMetaData interface o DatabaseMetaData interface o RowSet interface A list of popular classes of JDBC API is given below: o DriverManager class o Types class There are four types of JDBC drivers: o JDBC-ODBC Bridge Driver, o Native Driver,
  • 3. o Network Protocol Driver, and o Thin Driver The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver.
  • 4. Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge. Advantages: o easy to use. o can be easily connected to any database. Disadvantages: o Performance degraded because JDBC method call is converted into the ODBC function calls. o The ODBC driver needs to be installed on the client machine.
  • 5. Topic: Establishing Connectivity There are 5 steps to connect any java application with the database using JDBC. These steps are as follows: o Register the Driver class o Create connection o Create statement o Execute queries o Close connection 1) Register the driver class The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.
  • 6. Syntax of forName() method 1. public static void forName(String className)throws ClassNotFoundE xception Example to register the OracleDriver class Here, Java program is loading oracle driver to establish database connection. Class.forName("oracle.jdbc.driver.OracleDriver"); 2) Create the connection object The getConnection() method of DriverManager class is used to establish Connection with the database. Syntax of getConnection() method public static Connection getConnection(String url)throws SQLExceptio n public static Connection getConnection(String url,String username,String p assword) throws SQLException Example to establish connection with the Oracle database Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost: 1521:xe","system","system"); 1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver. 2. Connection URL: The connection URL for the oracle10G database is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is the driver, localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port number and XE is the Oracle service name. 3. Username: The default username for the oracle database is system.
  • 7. 4. Password: It is the password given by the user at the time of installing the oracle database. 3) Create the Statement object The createStatement() method of Connection Interface is used to create statement. The object of statement is responsible to execute queries with the database. Syntax of createStatement() method 1. public Statement createStatement() throws SQLException Example to create the statement object 1. Statement stmt=con.createStatement(); 4) Execute the query The executeQuery() method of Statement interface is used to execute queries to the database.This method returns the object of ResultSet that can be used to get all the records of a table. Syntax of executeQuery() method 1. public ResultSet executeQuery(String sql) throws SQLException Example to execute query ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next()) { System.out.println(rs.getInt(1)+" "+rs.getString(2)); }
  • 8. 5) Close the connection object By closing connection object statement and ResultSet will be closed automatically The close() method of Connection interface is used to close the connection. Syntax of close() method public void close() throws SQLException Example to close connection con.close();
  • 9. Creating and Executing SQL statement Executing SQL on the Connection involves two further objects: • we create a Statement object, to which we pass the SQL to be executed and set any required options; • we read the result of the query via a ResultSet object. Creating a Statement object is simple once we have our Connection: Connection con =DriverManager.getConnection(); Statement stmt = con.createStatement(); Then, to execute a simple SQL statement and get the corresponding result, we write something as follows: int id = ... get ID from somewhere ... String sql = "SELECT Name FROM Users WHERE Id = " + id; ResultSet rs = st.executeQuery(sql); // ... read from result set ... The executeQuery() method returns a ResultSet object from which the result data can be read. For a simple SELECT query such as this, we would always expect a result set to be returned, which would be empty if no rows were returned. The ResultSet object returned can then be queried to pull out the rows and colums of the result.
  • 10. Working With ResultSet Object Having obtained a database connection and executed a query via a Statement object, the next stage is to pull out the data from the ResultSet. A result set consists of zero or more rows. Let's suppose that our query on a User’s table returns rows in the following format: Id (INT) UserName (VARCHAR) FirstName (VARCHAR) Surname (VARCHAR) TimeRegistered (TIMESTAMP) 3 dsmith David Smith 2008-04-02 18:16:22 4 ntroberts Nigel Roberts 2008-05-01 20:11:01 6 bgsmithers Bill Smithers 2008-05-02 02:43:52 Now we can pull out the details of successive users from the result as follows: ResultSet rs = st.getResultSet(); try { while (rs.next()) { int id = rs.getInt(1); String userName = rs.getString(2); String firstName = rs.getString(3); String surname = rs.getString(4); Timestamp timeReg = rs.getTimestamp(5); // ... do something with these variables ... } } finally { con.close(); } Notice the repeated call to next(), which returns true if there is another row of data, and at the same time gets the ResultSet ready to start reading data from that next row. The code above illustrates the following points and topics: • Column numbers start at 1, not zero.
  • 11. • There are mappings between SQL and Java data types. For example, a SQL INT is mapped to a Java int; SQL VARCHARs are mapped to Java Strings. We call a get() method on the ResultSet that is appropriate to the type we want to retrieve. (As discussed on the next page, it turns out that these methods luckily can often perform conversion if we don't choose the exact type.) • The ResultSet and/or Statement needs to be closed. Whilst in emergencies they will be closed on finalization, it's preferable to close them explicitly as soon as they are no longer needed. Unfortunately, there are three different types of JDBC resource, all of which have a close() method! In a moment, we'll discuss when to close JDBC resources.