Download JDBC Introduction

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
no text concepts found
Transcript
JDBC Introduction :
•
The JDBC (Java Database Connectivity) API defines interfaces and classes for
writing database applications in Java by making database connections.
•
Using JDBC you can send SQL, PL/SQL statements to almost any relational
database.
•
You will learn how to create a table, insert values into it, query the table, retrieve
results, and update the table with the help of a JDBC Program example.
JDBC Architecture
•
Java application calls the JDBC library. JDBC loads a driver which talks to the
database. We can change database engines without changing database code.
JDBC Basics - Java Database Connectivity Steps :
• Before you can create a java jdbc connection to the database, you must first
import the java.sql package.
Steps:
•
•
•
•
1. Loading a database driver,
2. Creating a oracle jdbc Connection ,
3. Creating a jdbc Statement object,
4. Executing a SQL statement with the Statement object, and returning a java
Result Set.
1. Loading a database driver
• In this step of the jdbc connection process, we load the driver class by calling
Class.forName() with the Driver class name as an argument.
•
Once loaded, the Driver class creates an instance of itself.
•
A client can connect to Database Server through JDBC Driver. Since most of the
Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is
commonly used.
•
The return type of the Class.forName(String ClassName) method is "Class".
Class is a class in java.lang package.
Example
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Or any other driver
}
catch(Exception x)
{
System.out.println( "Unable to load the driver class!" );
}
2. Creating a oracle jdbc Connection
• The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver. DriverManager is considered the backbone of
JDBC architecture.
• DriverManager class manages the JDBC drivers that are installed on the system.
Its getConnection() method is used to establish a connection to a database
• It uses a username, password, and a jdbc url to establish a connection to the
database and returns a connection object.
• JDBC URL Syntax:: jdbc: <subprotocol>: <subname>
• Each driver has its own subprotocol
• Each subprotocol has its own syntax for the source
Example:( For example, we're using the jdbc odbc subprotocol, so the DriverManager
knows to use the sun.jdbc.odbc.JdbcOdbcDriver)
try
{
Connection dbConnection = DriverManager.getConnection(url, "loginName",
"Password")
}
catch( SQLException x )
{
System.out.println( "Couldn't get connection!" );
}
3. Creating a jdbc Statement object
• Once a connection is obtained we can interact with the database.
• Connection interface defines methods for interacting with the database via the
established connection.
• To execute SQL statements, you need to instantiate a Statement object from your
connection object by using the createStatement() method.
Statement statement = dbConnection.createStatement();
•
A statement object is used to send and execute SQL statements to a database.
Three kinds of Statements
• Statement: Execute simple sql queries without parameters.
Statement create Statement()  Creates an SQL Statement object.
• Prepared Statement: Execute precompiled sql queries with or without parameters.
Prepared Statement prepare Statement(String sql)  Returns a new Prepared Statement
object. Prepared Statement objects are precompiled SQL statements.
• Callable Statement: Execute a call to a database stored procedure.
Callable Statement prepare Call(String sql)  returns a new Callable Statement object.
Callable Statement objects are SQL stored procedure call statements.
4. Executing a SQL statement with the Statement object, and returning a java
Result Set.
• Statement interface defines methods that are used to interact with database via the
execution of SQL statements.
•
The Statement class has three methods for executing statements: execute Query(),
execute Update(), and execute() .
• For a SELECT statement, the method to use is execute Query .
Types of JDBC Drivers
• Type 1: JDBC-ODBC Bridge driver (Bridge)
• Type 2: Native-API/partly Java driver (Native)
•
Type 3: All Java/Net-protocol driver (Middleware)
• Type 4: All Java/Native-protocol driver (Pure)
Type 1: JDBC-ODBC Bridge driver
• The Type 1 driver translates all JDBC calls into ODBC calls and sends them to
the ODBC driver. ODBC is a generic API.
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database's
ODBC drivers are already available
Type 2: Native-API/partly Java driver
• The Type 2 driver converts JDBC calls into database-specific calls i.e. this driver
is specific to a particular database. Example: Oracle will have oracle native api.
Advantage
Type 2 drivers typically offer better performance than the JDBC-ODBC Bridge as the
layers of communication (tiers) are less than that of Type 1 and also it uses Native api
which is Database specific.
Type 3: All Java/Net-protocol driver
•
•
Type 3 database requests are passed through the network to the middle-tier server
The middle-tier then translates the request to the database. If the middle-tier
server can in turn use Type1, Type 2 or Type 4 drivers.
Advantage
• This driver is server-based, so there is no need for any vendor database
library to be present on client machines.
• This driver is fully written in Java and hence Portable. It is suitable for the web
• This driver is very flexible allows access to multiple databases using one driver.
• They are the most efficient amongst all driver types
Type 4: Native-protocol/all-Java driver
• The Type 4 uses java networking libraries to communicate directly with the
database server.
• Advantage
• Type 4 drivers are completely written in Java to achieve platform independence
and eliminate deployment administration issues. It is most suitable for the web.
• You don’t need to install special software on the client or server. Further, these
drivers can be downloaded dynamically.
Create 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:odbc:Exp";
String dbName = "jdbctutorial";
String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
String userName = "";
String password = "";
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)
{
System.out.println("Table all ready exists!");
}
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Insert values
import java.sql.*;
public class InsertValues
{
public static void main(String[] args)
{
System.out.println("Inserting values in Mysql database table!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
try
{
Class.forName(driver);
con = DriverManager.getConnection(url+db,"root","root");
try
{
Statement st = con.createStatement();
int val = st.executeUpdate("INSERT employee VALUES("+13+","+"'Aman'"+")");
System.out.println("1 row affected");
}
catch (SQLException s)
{
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
•
Get All Rows
import java.sql.*;
public class GetAllRows
{
public static void main(String[] args)
{
System.out.println("Getting All Rows from a table!");
Connection con = null;
String url = "jdbc:odbc:tablesel";
String db = "jdbctutorial";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String user = "";
String pass = "";
try
{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db, user, pass);
try
{
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employee6");
System.out.println("Emp_code: " + "\t" + "Emp_name: ");
while (res.next())
{
int i = res.getInt("Emp_code");
String s = res.getString("Emp_name");
System.out.println(i + "\t\t" + s);
}
con.close();
}
catch (SQLException s)
{
System.out.println("SQL code does not execute.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Delete All Rows
import java.sql.*;
public class DeleteTable
{
public static void main(String[] args)
{
System.out.println("Tabel Deletion 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();
st.executeUpdate("DROP TABLE Employee1");
System.out.println("Table Deletion process is completly successfully!");
}
catch(SQLException s)
{
System.out.println("Table is not exists!");
}
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Java Servlet
Java Servlet A program (running on a web server) that dynamically generates some output as
its reaction to a request
•
The purpose of a servlet is to create a Web page in response to a client request
•
Servlets are the Java platform technology of choice for extending and enhancing web
servers.
•
Servlets provide a component-based, platform-independent method for building webbased applications, without the performance limitations of CGI programs.
Applet vs. Servlet
• Applet: a java program that runs within the web browser.
• Servlet: a java program that runs within the web server.
• Big applets require long download time
• Applets do not have access to all the system resources
• Servlets are generic extensions to Java-enabled servers
• Servlets are secure, portable, and easy to use replacement for CGI
• Servlet is a dynamically loaded module that services requests from a Web server
Java Servlet
•
Servlets are written in Java, with a little HTML mixed in
– The HTML is enclosed in out.println( ) statements
•
When would you use servlets
– Page is based on user-submitted data e.g. search engines
– Data changes frequently e.g. weather-reports
– Page uses information from a databases e.g. on-line stores
Package javax. servlet: Main Classes
•
Defines the interface between Servlet Engine and Servlet
– Servlet
• independent of communication protocol (e. g. HTTP, FTP)
– ServletRequest
• information about the request
– ServletResponse
• generating and sending the response to the browser
– ServletConfig
• provides initialization parameters for a Servlet (from web. xml)
– ServletContext
• describes run time environment of the Servlet
Servlet Life Cycle
• When the Servlet instance has been created, the container will call init()
• Now the Servlet is ready for processing user requests
– service() is called for processing a request
– the Servlet remains loaded and ready after a request is processed
• destroy() is called before a Servlet is deleted
– time of deletion is not defined
A Servlet’s Job
• Servlets are executed within the Java Virtual Machine
• Because the servlet is running on the server side, it does not depend on browser
compatibility
• Read explicit data sent by client (form data)
• Read implicit data sent by client (request headers)
• Generate the results
• Send the explicit data back to client (HTML)
• Send the implicit data to client (status codes and response headers)
Applications of Java Servlets
• Building e-commerce store fronts
• Servlet builds an online catalog based on the contents of a database
• Customer places an order, which is processed by another servlet
• Servlets as wrappers for legacy systems
• Servlets interacting with EJB applications
Advantages of Servlets
• Efficiency, Persistency .
• Servlets can maintain state between requests.
• Portability- Since servlets are written in Java, they are platform independent .
• Large class library – network, file, database, distributed object components,
security, etc.
Java Servlet Architecture
•
•
•
Two packages make up the servlet architecture
– javax.servlet
– javax.servlet.http
javax.servlet
– Contains generic interfaces and classes that are implemented and extended
by all servlets
javax.servlet.http
– Contains classes that are extended when creating HTTP-specific servlets
•
•
The heart of servlet architecture is the interface class javax.servlet.Servlet
It provides the framework for all servlets.
•
Defines five basic methods – init, service, destroy, getServletConfig and
getServletInfo
A Simple Servlet That Generates Plain Text
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest request,
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
Output
HttpServletResponse response)
Generating HTML
public class HelloWWW extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" +
"<BODY>\n" +
"<H1>Hello WWW</H1>\n" +
"</BODY></HTML>");
}}
Servlet Life Cycle Summary
• init
– Executed once when the servlet is first loaded.
– Not called for each request.
• service
– Called in a new thread by server for each request. Dispatches to doGet,
doPost, etc.
– Do not override this method!
• doGet, doPost, doXxx
– Handles GET, POST, etc. requests.
– Override these to provide desired behavior.
• Destroy
– Called when server deletes servlet instance.
– Not called after each request.
JSP (Java Server Pages)
•
•
•
•
JSP (Java Server Pages) is an alternate way of creating servlets
JSP is written as ordinary HTML, with a little Java mixed
JSP files must have the extension .jsp
JSP is translated into a Java servlet, which is then compiled. Servlets are run in
the usual way.
JSP scripting elements
• There is more than one type of JSP “tag,” depending on what you want done with
the Java.
• <%= expression %>
– The expression is evaluated and the result is inserted into the HTML page
• <% code %>
– The code is inserted into the servlet's service method
– This construction is called a scriptlet
• <%! declarations %>
– The declarations are inserted into the servlet class, not into a method
Example JSP
• <HTML>
<BODY>
Hello! The time is now <%= new java.util.Date() %>
</BODY>
</HTML>
• Notes:
–
–
The <%= ... %> tag is used, because we are computing a value and
inserting it into the HTML
The fully qualified name (java.util.Date) is used, instead of the short name
(Date), because we haven’t yet talked about how to do import declarations
Variables
• You can declare your own variables, as usual.
• JSP provides several predefined variables
– request : The HttpServletRequest parameter
– response : The HttpServletResponse parameter
– session : The HttpSession associated with the request, or null if there is
none
– out : A JspWriter (like a PrintWriter) used to send output to the client
• Example:
– Your hostname: <%= request.getRemoteHost() %>