Documente Academic
Documente Profesional
Documente Cultură
VC++,VB
Java programs
ODBC or JDBC
For different databases, database client need not talk in different ways. Database client talks through ODBC API or JDBC API and the API talks to the database server. Database Server listens to a port and responds only to SQL commands passed by ODBC or JDBC.
ODBC is a C language API, not a Java API. Java is object oriented and C is not. C uses pointers and dangerous programming constructs that Java does not support. ODBC drivers must be installed on client machines. i.e.,the Applet that has to access to databases needs a driver in the client side. If the driver is a ODBC driver, the applet does not execute. A Pure Java solution allows JDBC drivers to be automatically installed along with the applet.
JDBC Type 2 Driver -- use platform-specific APIs for data access JDBC Type 3 Driver -- 100% Java, use a net protocol to access a remote listener and map calls into vendor-specific calls JDBC Type 4 Driver -- 100% Java
Most efficient of all driver types
ODBC (Open DataBase Connectivity) is a standard software API designed to be independent of specific programming languages Sun provides a JDBC/ODBC implementation
This driver uses Microsofts ODBC 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 be preinstalled on a client computer before it can be used. Oracle
ODBC
Server JDBC ODBC Bridge JDBC ODBC
Database Client
DB2
These drivers talks to database servers using Call Level Interface. There are certain C language libraries for connecting to Oracle , DB2 or any other database. This driver will use those C language libraries for speaking with the particular database. These drivers are implemented in a combination of binary code in Java and must be installed on a client machine.
Vendor specific protocol Native partly Java driver Database Server
Database Client
This driver translates JDBC calls into a DBMS- independent net protocol (HTTP) which is then translated to a DBMS protocol by a server. This net server middleware is able to connect its pure Java clients to many different databases. The specific protocol used depends on the vendor. This is the best solution for applets which wants to talk to database directly without using servlets.
Pure Java driver Oracle Server
Database Client
DB2 server
SQL server
This driver category consists of pure Java driver. This Driver uses vendor specific database protocol of the database server directly.
Vendor specific protocol Pure Java driver Database Server
Database Client
Type I Bridge
ODBC
ODBC Driver
JDBC
Type II Native
CLI (.lib)
Middleware Server
Type IV Pure
Class.forName(oracle.jdbc.driver.OracleDriver)
1. Loading the Driver Class.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);
4. Creating the statement Statement stmt=con.createStatement(); 5. Execute the corresponding SQL statements. ResultSet rs=stmt.executeQuery(select * from Table where empno=5); 6. Reading the values from the Resultset. while(rs.next()) { String s=rs.getString(empname); double sal=rs.getDouble(empsal); }
executeQuery() used to execute only SQL query statements (DQL) Returns a ResultSet object which can interact with Resulted Buffer data in database. executeUpdate() used to execute either insert, update or delete statements(DML) Returns no of rows effected by the operation. execute() used to execute any type of statements like create, alter, drop (DDL) Returns true if command executed successfully, otherwise returns false.
<%@ page language="java" import="java.sql.*" %> <html> <body bgcolor="wheat"><center> <h2>Registered Users Details</h2> <table border=2 > <tr><th>User Name</th><th>Password</th> <th>EMail ID</th><th>Phone Number</th></tr> <% try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection( "jdbc:odbc:mysqlDSN","root","root"); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select * from userdetails");
while(rs.next()) { %> <tr><td><%= rs.getString(1) %></td> <td><%=rs.getString(2) %></td> <td><%= rs.getString(3) %></td> <td><%= rs.getString(4) %></td></tr> <% } }catch(Exception e) { out.println(e.getMessage()); } %> </table> </center> </body> </html>
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 of columns selected in select query. getColumnName(int colnumber) returns the name of the column getColumnType(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<count; i++) System.out.print(rsmd.getColumnName(i) + \t); System.out.println(); while(rs.next() { for(int j=0; j<count; j++) System.out.println(rs.getString(i) + \t); System.out.println(); } rsmd.close(); rs.close();
Interface Summary
ConnectionPoolDataSou A factory for PooledConnection objects. rce A factory for connections to the physical data source that this DataSource DataSource object represents. PooledConnection RowSet RowSetInternal RowSetListener RowSetMetaData RowSetReader RowSetWriter XAConnection XADataSource An object that provides hooks for connection pool management. The interface that adds support to the JDBC API for the JavaBeans TM component model. The interface that a RowSet object implements in order to present itself to a RowSetReader or RowSetWriter object. An interface that must be implemented by a component that wants to be notified when a significant event happens in the life of a RowSet object. An object that contains information about the columns in a RowSet object. The facility that a disconnected RowSet object calls on to populate itself with rows of data. An object that implements the RowSetWriter interface, called a writer. An object that provides support for distributed transactions. A factory for XAConnection objects that is used internally.
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)); }
JDBC Type
BIT TINYINT SMALLINT INTEGER BIGINT REAL FLOAT DOUBLE BINARY VARBINARY LONGVARBINARY CHAR VARCHAR LONGVARCHAR
Java Type
boolean byte short int long float double byte[]
JDBC Type
NUMERIC DECIMAL DATE TIME TIMESTAMP CLOB BLOB ARRAY DISTINCT STRUCT REF JAVA_OBJECT
Java Type
BigDecimal java.sql.Date java.sql.Timestamp Clob* Blob* Array* mapping of underlying type Struct* Ref* underlying Java class
String
24
JDBC
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)
User input
View View selection events Controller
JavaBean
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 new development, great community, many applications are developed in 1.x
The Apache Struts web framework is for creating Java web applications. Web applications based on JSP Pages sometimes commingle database 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-ViewController (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 create web applications that utilize a MVC architecture. The framework provides three key components:
A "request" handler provided by the application developer that is mapped to a standard URI. A "response" handler that transfers control to another resource which completes the response. A tag library that helps developers create interactive form-based applications with server pages.
The controller servlet recieves all the requests. It searches the properties file for appropriate request handler, depending upon the request URL. Invokes the request handler returned by step2 and passes control to it. The request handler handles the request, including business logic methods invocation, form validation etc., The request handler returns the name of the view to be displayed. The controller servlet dispatches the request to the view returned by the request handler. View is sent as a response to the user.
Model-View-Controller (MVC) framework Used for constructing web applications based Servlets and JSP technologies
Struts application is a genuine Web application that should be able to run on any Sevlet container including all J2EE compliant App servers Singleton, composition view, delegate Easy to use and learn
Pattern oriented
Takes much of the complexity out of building your own MVC framework Encourages good design practice and modeling Easy to learn and use Feature-ric Many supported 3rd-party tools Flexible and extensible Large user community Stable and mature Open source
Integrates well with J2EE Good custom tags support Easy to retain input form state Unified error handling programmatically and declaratively Integration with Tiles framework Clear delineation of responsibility makes long term maintenance easier (more modular)
Central controller (ActionServlet) mediates application flow and delegates to appropriate handler called Action Action Handlers can use model components Model encapsulates business logic or state Control forwarded back through the Controller to the appropriate View
The forwarding can be determined by consulting a set of mappings in configuration file
A) The web application is deployed. The server reads the deployment descriptor file(web.xml). Loads the ActionServlet 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 web browser. Browser tries to load register.jsp E) user enters username and password and press the submit button. F) form invokes the action-URL and send request to server with the action /reg.do. G) control transfer to the servlet-mapping tag in web.xml and ActionServlet traps the request-data.
H) ActionServlet reads the entries of strutsconfig.xml file. I) It locates the action /reg in actionmapping tag. J) It reads name of Action Form. K) from form-beans tag it locates the form-bean class and loads that class. L) object of form bean is populated and the property values in register.jsp transferred and stored in form bean object using setter methods. M) ActionServlet reads the Action sub class name in struts-config.xml and loads the sub class.
N) the object of Action sub class and its execute() 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 action tag and find the filename to forward the control. Q) either success.jsp/failure.jsp is displayed as a result.