Download JDBC Statements

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Commitment ordering wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Microsoft Access wikipedia , lookup

IMDb wikipedia , lookup

Serializability wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Functional Database Model wikipedia , lookup

Oracle Database wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

SQL wikipedia , lookup

Ingres (database) wikipedia , lookup

Database wikipedia , lookup

Concurrency control wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

PL/SQL wikipedia , lookup

Versant Object Database wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Clusterpoint wikipedia , lookup

ContactPoint wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Transcript
JDBC
Database Programming in Java
Prepared by.,
Mrs.S.Amudha AP/SWE
Agenda
•
•
•
•
•
Overview of Databases and Java
Overview of JDBC
JDBC APIs
Types of JDBC Drivers
Other Database Techniques
2
Introduction
• JDBC is Java application programming interface
that allows the Java programmers to access
database management system from Java code.
• It was developed by JavaSoft, a subsidiary of
Sun Microsystems.
• It is a java API which enables the java programs
to execute SQL statements.
• JDBC provides methods for querying and
updating the data in Relational Database
Management system such as SQL, Oracle etc.
3
Introduction
• In short JDBC helps the programmers to write
java applications that manage these three
programming activities:
1. It helps us to connect to a data source, like a
database.
2. It helps us in sending queries and updating
statements to the database and
3. Retrieving and processing the results received
from the database in terms of answering to your
query.
4
Product Components of JDBC
JDBC has four Components:
1. The JDBC API.
• The JDBC application programming interface provides the facility for
accessing the relational database from the Java programming language
2. The JDBC Driver Manager.(Backbone)
• The JDBC Driver Manager is a very important class that defines
objects which connect Java applications to a JDBC driver
3. The JDBC Test Suite.
• The function of JDBC driver test suite is to make ensure that the
JDBC drivers will run user's program or not
4. The JDBC-ODBC Bridge.
• The JDBC-ODBC bridge, also known as JDBC type 1 driver is a
database driver that utilize the ODBC driver to connect the database.
• This driver translates JDBC method calls into ODBC function calls
5
JDBC Architecture
6
JDBC Architecture
The JDBC API uses a Driver Manager and database-specific
drivers to provide transparent connectivity to heterogeneous
databases.

The JDBC driver manager ensures that the correct driver is
used to access each data source.

The Driver Manager is capable of supporting multiple
concurrent drivers connected to multiple heterogeneous
databases.

The location of the driver manager with respect to the JDBC
drivers and the servlet is shown in Figure

7
Layers of the JDBC Architecture
A JDBC driver translates standard JDBC calls into a network or database protocol or
into a database library API call that facilitates communication with the database
8
Type 1 JDBC-ODBC Bridge
• Type 1 drivers act as a "bridge"
between JDBC and another
database connectivity
mechanism such as ODBC.
•
The JDBC- ODBC bridge
provides JDBC access using
most standard ODBC drivers.
•
In this driver the java
statements are converted to a
jdbc statements.
• JDBC statements calls the
ODBC by using the JDBCODBC Bridge
9
Type 2 Java to Native API
• Type 2 drivers use the
Java Native Interface
(JNI) to make calls to
a local database
library API.
• This driver converts
the JDBC calls into a
database specific call
for databases such as
SQL, ORACLE etc.
10
• This driver
Type 3 Java to Network Protocol Or All- Java
Driver
• Type 3 drivers are pure Java
drivers that use a proprietary
network protocol to communicate
with JDBC middleware on the
server.
• The middleware then translates
the network protocol to databasespecific function calls.
• Type 3 drivers are the most
flexible JDBC solution because
they do not require native
database libraries on the client
11 many different
and can connect to
Type 4 Java to Database Protocol
• Type 4 drivers are pure Java
drivers that implement a
proprietary database protocol
(like Oracle's SQL*Net) to
communicate directly with the
database.
• Like Type 3 drivers, they do not
require native database libraries
and can be deployed over the
Internet without client
installation.
• One drawback to Type 4 drivers
12
is that they are database
specific.
JDBC Statements
• A JDBC statement object is used to send your
SQL statement to the database server
• A JDBC statement is associated with an open
connection and not any single SQL statement
• JDBC provides three classes of SQL statement
– Statement
– PreparedStatement
– CallableStatement
13
Creating JDBC Statement
Statement stmt = con.createStatement();
String createCS4400 = “Create table CS4400 “+
“(SSN Integer not null, Name
VARCHAR(32), “+ “Marks Integer)”;
stmt.executeUpdate(createCS4400);
String insertCS4400 = “Insert into CS4400
values “+“(123456789,abc,100)”;
stmt.executeUpdate(insertCS4400);
14
Create JDBC Statement (contd..)
String queryCS4400 = “select * from CS4400”;
ResultSet rs = Stmt.executeQuery(queryCS4400);
While (rs.next()) {
int ssn = rs.getInt(“SSN”);
String name = rs.getString(“NAME”);
int marks = rs.getInt(“MARKS”);
}
Note: column number can also be used in place of
column name.Refer to java.sql.ResulSet API for
15
more details
Prepared Statement
• Unlike “Statement” it is given a SQL statement
when it is created.
• Used when you want to execute “Statement” object
many times
E.g
String insert = “Insert into CS4400 (?,?,?)”;
PreparedStatement stmt2 =
con.prepareStatement(insert);
stmt2.setInt(1,123456789);
stmt2.setString(2,abc);
stmt2.setInt(3,100);
16
stmt2.executeUpdate();
Prepared Statement (cont..)
• Executing Select Statement
e.g
String query =“SELECT Name from CS4400
where SSN=?”;
PreparedStatement stmt2 =
con.prepareStatement(query);
Stmt2.setInt(1,SSN);
ResultSet rs = stmt2.executeUpdate();
While (rs.next())
System.out.println(rs.getString(Name);
17
Callable Statement
• Used for executing stored procedures
• Example
String createProcedure = “Create Procedure
ShowGoodStudents” + “as Select Name from
CS4400 where Marks > 90)”;
Stmt.executeUpdate(createProcedure);
CallableStatement cs = con.prepareCall(“(call
ShowGoodStudents)”);
ResultSet rs = cs.executeQuery();
18
Basic steps in writing a JDBC Application
• JDBC Steps to be followed while writing JDBC
program:
* Loading Driver
* Establishing Connection
* Executing Statements
* Getting Results
* Closing Database Connection
19
Loading Driver
• Loading Database driver is very first step
towards making JDBC connectivity with the
database.
• It is necessary to load the JDBC drivers before
attempting to connect to the database.
• The JDBC drivers automatically register
themselves with the JDBC system when loaded.
Here is the code for loading the JDBC driver:
• Class.forName(driver).newInstance();
20
Establishing Connection
• In the above step we have loaded the database driver to be
used.
• Now its time to make the connection with the database
server.
• In the Establishing Connection step we will logon to the
database with user name and password.
• Following code we have used to make the connection
with the database:
con = DriverManager.getConnection(url+db, user, pass);
21
Executing Statements
• In the previous step we established the
connection with the database, now its time to
execute query against database.
• You can run any type of query against database
to perform database operations.
• In this example we will select all the rows from
employee table.
• Here is the code that actually execute the
statements against database:
• ResultSet res = st.executeQuery( "SELECT *
22
FROM employee" );
Getting Results
• In this step we receives the result of execute statement.
In this case we will fetch the employees records from
the recordset object and show on the console. Here is the
code:
while (res.next()) {
String employeeName = res.getInt( "
employee_name " );
System.out.println( employeeName );
}
23
Closing Database Connection
• Finally it is necessary to disconnect from the database
and release resources being used.
• If you don’t close the connection then in the production
environment your application will fail due to hanging
database connections.
• Here is the code for disconnecting the application from
database:
• con.close();
24
Creating a Database Table
import java.sql.*;
public class CreateTable{
public static void main(String[] args) {
System.out.println("Table Creation Example!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driverName = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try{
Class.forName(driverName).newInstance();
con = DriverManager.getConnection(url+dbName, userName, password);
try{
Statement st = con.createStatement();
String table = "CREATE TABLE Employee11(Emp_code integer, Emp_name varchar(10))";
st.executeUpdate(table);
System.out.println("Table creation process successfully!");
catch(SQLException s){
con.close();
catch (Exception e){
}
System.out.println("Table all ready exists!");
}
}
e.printStackTrace();
}
}
}
25
Transactions and JDBC
• JDBC allows SQL statements to be grouped together into
a single transaction
• Transaction control is performed by the Connection
object, default mode is auto-commit, I.e., each sql
statement is treated as a transaction
• We can turn off the auto-commit mode with
con.setAutoCommit(false);
• And turn it back on with con.setAutoCommit(true);
• Once auto-commit is off, no SQL statement will be
committed until an explicit is invoked con.commit();
• At this point all changes done by the SQL statements will
be made permanent in the database.
26
Handling Errors with Exceptions
• Programs should recover and leave the database in a
consistent state.
• If a statement in the try block throws an exception or
warning, it can be caught in one of the corresponding
catch statements
• How might a finally {…} block be helpful here?
• E.g., you could rollback your transaction in a
catch { …} block or close database connection and free
database related resources in finally {…} block
27
JDBC references
• JDBC Data Access API – JDBC Technology
Homepage
– http://java.sun.com/products/jdbc/index.ht
ml
• JDBC Database Access – The Java Tutorial
– http://java.sun.com/docs/books/tutorial/jdbc/
index.html
• JDBC Documentation
– http://java.sun.com/j2se/1.4.2/docs/guide/jd
bc/index.html
28
29