8-JDBC

download 8-JDBC

of 41

Transcript of 8-JDBC

  • 8/12/2019 8-JDBC

    1/41

  • 8/12/2019 8-JDBC

    2/41

    Remote Database Access

    User DatabaseClient APIDatabase

    ServerDatabase

    VC++,VB

    Java programsODBC

    or JDBCFor different databases, database client need not talk in different ways.

    Database client talks through ODBC API or JDBC API and the API talks tothe database server.

    Database Server listens to a port and responds only to SQL commandspassed by ODBC or JDBC.

  • 8/12/2019 8-JDBC

    3/41

    ODBC is a C language API, not a Java API. Java isobject oriented and C is not.C uses pointers and dangerous programmingconstructs that Java does not support.

    ODBC drivers must be installed on client machines.i.e.,the Applet that has to access to databasesneeds a driver in the client side. If the driver is aODBC driver, the applet does not execute.

    A Pure Java solution allows JDBC drivers to beautomatically installed along with the applet.

  • 8/12/2019 8-JDBC

    4/41

    There are four types of drivers: JDBC Type 1 Driver -- JDBC/ODBC Bridge drivers

    ODBC (Open DataBase Connectivity) is a standardsoftware API designed to be independent of specificprogramming languagesSun provides a JDBC/ODBC implementation

    JDBC Type 2 Driver -- use platform-specific APIsfor data access

    JDBC Type 3 Driver -- 100% Java, use a net protocolto access a remote listener and map calls intovendor-specific calls

    JDBC Type 4 Driver -- 100% JavaMost efficient of all driver types

  • 8/12/2019 8-JDBC

    5/41

    This driver uses Microsofts OD C driver to

    communicate with Database servers.It is an attempt to use the existing ODBC drivers.It is implemented using C and Java and must bepreinstalled on a client computer before it can be

    used.

    DatabaseClient

    JDBC ODBCBridge

    OracleServer

    DB2

    SQL Server

    ODBC

    ODBC

    ODBC JDBC

  • 8/12/2019 8-JDBC

    6/41

  • 8/12/2019 8-JDBC

    7/41

    These drivers talks to database servers using Call LevelInterface.There are certain C language libraries for connecting toOracle , DB2 or any other database.This driver will use those C language libraries for speakingwith the particular database.

    These drivers are implemented in a combination of binarycode in Java and must be installed on a client machine.

    DatabaseClient

    Native partly Java

    driverDatabase

    Server

    Vendor specific

    protocol

  • 8/12/2019 8-JDBC

    8/41

  • 8/12/2019 8-JDBC

    9/41

    This driver translates JDBC calls into a DBMS- independent netprotocol HTTP) which is then translated to a DBMS protocol by aserver.This net server middleware is able to connect its pure Java clientsto many different databases.The specific protocol used depends on the vendor.

    This is the best solution for applets which wants to talk todatabase directly without using servlets.

    Database accessserver

    Pure Java driver

    DatabaseClient

    OracleServer

    DB2 server

    SQL server

  • 8/12/2019 8-JDBC

    10/41

  • 8/12/2019 8-JDBC

    11/41

    This driver category consists of pure Javadriver.This Driver uses vendor specific databaseprotocol of the database server directly.

    DatabaseClient

    Pure Java

    driver

    Database

    Server

    Vendor specific

    protocol

  • 8/12/2019 8-JDBC

    12/41

  • 8/12/2019 8-JDBC

    13/41

    JDBC

    Type IBridge

    Type IINative

    Type III

    Middleware

    Type IVPure

    ODBC ODBCDriver

    CLI (.lib)

    Middleware

    Server

  • 8/12/2019 8-JDBC

    14/41

    import JDBC packages (java.sql.*)Load the JDBC drivers Class.forName (oracle.jdbc.driver.OracleDriver )

    Connect to the database Connection conn =

    DriverManager.getConnection(url,userid,passwd) jdbc:oracle:drivertype@database

    Interact with DB using JDBCDisconnect from DB

  • 8/12/2019 8-JDBC

    15/41

    1. Loading the DriverClass.forName (sun.jdbc.odbc.JdbcOdbcDriver );

    2. Constructing URL for the database.

    String url = jdbc:odbc:dsn ;

    3. Getting the Connection.Connection

    con=DriverManager.getConnection(url,userid,pwd);

  • 8/12/2019 8-JDBC

    16/41

    4. Creating the statementStatement stmt=con.createStatement();

    5. Execute the corresponding SQL statements.ResultSet rs=stmt.executeQuery (select * fromTable where empno =5);

    6. Reading the values from the Resultset.while(rs.next()){String s=rs.getString (empname ); double sal=rs.getDouble (empsal );

    }

  • 8/12/2019 8-JDBC

    17/41

    executeQuery()used to execute only SQL query statements (DQL)Returns a ResultSet object which can interact withResulted Buffer data in database.

    executeUpdate() used to execute either insert, update or deletestatements(DML)Returns no of rows effected by the operation.

    execute()

    used to execute any type of statements likecreate, alter, drop (DDL)Returns true if command executed successfully,otherwise returns false.

  • 8/12/2019 8-JDBC

    18/41

    boolean hasresults=stmt.execute(selectstatement);

    if(hasresults){ResultSet rs=stmt.getResultSet( );

    String str=rs.getString(empnam); ..

    }

  • 8/12/2019 8-JDBC

    19/41

    Registered Users Details

    User NamePasswordEMail IDPhone Number

  • 8/12/2019 8-JDBC

    20/41

    while(rs.next()){

    %>

  • 8/12/2019 8-JDBC

    21/41

    Retrieve Data about Result is done through ResultSetMetaData class object.We can creat it by calling getMetaData() method of ResultSet.

    getColumnCount() returns no of columns in resultset according to the no ofcolumns selected in select query.getColumnName(int colnumber) returns the name of the columngetColumnType(int colnumber) returns the type of the column

    Ex:ResultSet rs = st.executeQuery(select * from loginusers ); ResultSetMetaData rsmd = rs.getMetaData();int count = rsmd.getColumnCount();for( int i=0; i

  • 8/12/2019 8-JDBC

    22/41

  • 8/12/2019 8-JDBC

    23/41

    import java.sql.*;import javax.sql.*;import javax.sql.rowset.*;public class JDBCRowSetExample {

    public static void main(String[] args) throws Exception {Class.forName (com.mysql.jdbc.Driver ); JdbcRowSet rs = new JdbcRowSetImpl();

    rs.setUrl ( jdbc:mysql://localhost /test); rs.setUsername (root); rs.setPassword (root); rs.setCommand (select * from loginusers ); rs.execute();System.out.println (username \t password);

    while (rs.next()) {System.out.print(rs.getString(1));System.out.println (\t" + rs.getString(2));

    }

    }

    }

  • 8/12/2019 8-JDBC

    24/41

    JDBC24

    JDBC Type Java Type BIT boolean TINYINT byte SMALLINT short INTEGER int BIGINT long REAL float FLOAT double DOUBLE BINARY byte[] VARBINARY LONGVARBINARY

    CHAR String VARCHAR LONGVARCHAR

    JDBC Type Java Type NUMERIC BigDecimal DECIMAL DATE java.sql.Date TIME java.sql.Timestamp TIMESTAMP CLOB Clob * BLOB Blob * ARRAY Array * DISTINCT mapping of underlying type STRUCT Struct * REF Ref * JAVA_OBJECT underlying Java class

    *SQL3 data type supported in JDBC 2.0

  • 8/12/2019 8-JDBC

    25/41

    Frameworks: Provides abstraction of a particular concept Defines how these abstractions work together to

    solve a problem Framework components are reusable Organizes patterns at higher level Provides generic behaviour (many different

    applications can be built with the use of the same

    application)

  • 8/12/2019 8-JDBC

    26/41

    View

    Model

    Controller

    Change notification

    Query state

    View selection

    User input

    Change state

    events

  • 8/12/2019 8-JDBC

    27/41

    Web Browser

    JSP

    JavaBeanServlet

    Demo Model 2 example

  • 8/12/2019 8-JDBC

    28/41

    Created in 2000 by Craig R. McClanahan Donated to ASF in 2000 Most popular release: 1.3.8 Latest stable release is 2.3.4.1 1.x will be around - there is newdevelopment, great community, many applications are developed in 1.x

  • 8/12/2019 8-JDBC

    29/41

    The Apache Struts web framework is for creating Java webapplications.

    Web applications based on JSP Pages sometimes commingledatabase code, page design code, and control flow code.In practice, we find that unless these concerns are separated,larger applications become difficult to maintain.One way to separate the logics is to use a Model-View-Controller (MVC) architecture.The Model represents the business or database code,The View represents the page design code.The Controller represents the navigational code.The Struts framework is designed to help developers createweb applications that utilize a MVC architecture.

    The framework provides three key components: A "request" handler provided by the application developer that ismapped to a standard URI.

    A "response" handler that transfers control to another resource whichcompletes the response.

    A tag library that helps developers create interactive form-basedapplications with server pages.

  • 8/12/2019 8-JDBC

    30/41

  • 8/12/2019 8-JDBC

    31/41

    The controller servlet recieves all the requests.It searches the properties file for appropriate requesthandler, depending upon the request URL.Invokes the request handler returned by step2 andpasses control to it.The request handler handles the request, includingbusiness logic methods invocation, form validationetc.,The request handler returns the name of the view tobe displayed.The controller servlet dispatches the request to theview returned by the request handler.View is sent as a response to the user.

  • 8/12/2019 8-JDBC

    32/41

    Model-View-Controller (MVC) frameworkUsed for constructing web applications basedServlets and JSP technologies Struts application is a genuine Web application that

    should be able to run on any Sevlet containerincluding all J2EE compliant App serversPattern oriented Singleton, composition view, delegate Easy to use and learnIncludes custom tag libraries

  • 8/12/2019 8-JDBC

    33/41

    Takes much of the complexity out of building yourown MVC frameworkEncourages good design practice and modelingEasy to learn and use

    Feature-ricMany supported 3rd-party toolsFlexible and extensibleLarge user communityStable and matureOpen source

  • 8/12/2019 8-JDBC

    34/41

    Integrates well with J2EEGood custom tags supportEasy to retain input form state

    Unified error handling programmatically anddeclarativelyIntegration with Tiles frameworkClear delineation of responsibility makes long

    term maintenance easier (more modular)

  • 8/12/2019 8-JDBC

    35/41

  • 8/12/2019 8-JDBC

    36/41

    Central controller (ActionServlet) mediatesapplication flow and delegates to appropriatehandler called ActionAction Handlers can use model componentsModel encapsulates business logic or stateControl forwarded back through theController to the appropriate View

    The forwarding can be determined by consulting aset of mappings in configuration file

  • 8/12/2019 8-JDBC

    37/41

    3 Major Components in Struts Servlet controller (Controller) Java Server Pages or any other presentation

    technology (View) Application Business Logic in the form of whatever

    suits the application (Model)Struts is focused on Controller Struts is Model and View independent

    Struts can use any Model and View technologies

  • 8/12/2019 8-JDBC

    38/41

  • 8/12/2019 8-JDBC

    39/41

    A) The web application is deployed. The server readsthe deployment descriptor file(web.xml). Loads theActionServlet class on start.B) creates an object of ActionServlet.C) set the init- parameter config with its parameter. D) user gives request to the web application on webbrowser. Browser tries to load register.jspE) user enters username and password and press thesubmit button.

    F) form invokes the action-URL and send request toserver with the action / reg.do . G) control transfer to the servlet-mapping tag inweb.xml and ActionServlet traps the request-data.

  • 8/12/2019 8-JDBC

    40/41

    H) ActionServlet reads the entries of struts-config.xml file.I) It locates the action / reg in actionmappingtag.

    J) It reads name of Action Form.K) from form-beans tag it locates the form-beanclass and loads that class.L) object of form bean is populated and theproperty values in register.jsp transferred andstored in form bean object using setter methods.M) ActionServlet reads the Action sub class namein struts-config.xml and loads the sub class.

  • 8/12/2019 8-JDBC

    41/41

    N) the object of Action sub class and itsexecute() method is called and executed.O) according the values filled in jsp it desides O-a) ActionForward object is created with ok

    parameter. O-b) ActionForward object is created with fail

    parameter.P) ActionServlet reads the forward tags in actiontag and find the filename to forward the control.Q) either success.jsp/failure.jsp is displayed as aresult.