Download presentation
Presentation is loading. Please wait.
1
Chapter 14. JDBC, Java Server Pages, and MySQL
Database Management Systems (II) Chapter 14. JDBC, Java Server Pages, and MySQL © 2005 by Dr. G. Wan
2
JDBC, JSP and MySQL Alternative to Microsoft solutions for distributed database access Open-source software JDBC (not an acronym) Java Server Pages (JSP) using Apache/ Tomcat MySQL driver (an open-source DBMS developed by M. Mathews) Running in open environments Linux, and also Unix Proprietary systems such as Windows
3
JDBC JDBC Allowing programmers to connect to many databases with JDBC drivers For a listing of drivers, see: JDBC architecture and components (see figure) Objects in applications: Connection, Statement, ResultSet, ResultSetMetaData Driver manager Driver Database and DBMS
4
JDBC Architecture DBMS1 DB Driver Manager DBMS2 ODBC Driver
DBMS Driver1 DBMS Driver2 JDBC-ODBC Bridge DBMS1 DBMS2 ODBC Driver DB JDBC Architecture Applications Connection Statement ResultSet ResultSetMetaData CallableStatement PreparedStatement
5
JDBC driver types Type 1: JDBC-ODBC bridge drivers
Type 2: connects to the native API of the DBMS Type 3: translates JDBC into DBMS-independent network protocol Can be used for servlets and applets Type 4: translates JDBC into DBMS-specific network protocol
6
JDBC Driver Types Driver Type Characteristics 1
JDBC-ODBC bridge drivers. Provides a Java API that interfaces to an ODBC driver. Enables processing of ODBC data sources from Java 2 A Java API that connects to the native library of a DBMS product. The Java program and the DBMS must reside on the same machine, or the DBMS program must handle inter-machine communication, if not 3 A Java API that connects to a DBMS-independent network protocol. Can be used for servlets and applets 4 A Java API that connects to a DBMS-dependent network protocol. Can be used for servlets and applets JDBC Driver Types
7
Java programming language Java was designed to be portable
A Java program is not compiled into machine language, instead, into machine-independent bytecode (portability) Bytecode is interpreted by the Java virtual machine (JVM) JVM: a bytecode interpreter that is needed to run Java programs Different interpreters for different machine environments (Intel, Alpha, etc.)
8
Java performance Be interpreted, not as fast as code that has been translated into machine language This may or may not a problem, depending on the application’s workload.
9
A servlet is a Java program invoked via HTTP on the Web server
Java servlet A servlet is a Java program invoked via HTTP on the Web server The servlet uses the JVM running on the server Java applet An applet is Java bytecode that is designed to run on a client Applet bytecode is sent to the client machine using HTTP. It is read and interpreted by the Web browser. Most, if not all, Web browsers now run the Java virtual machine JVM servlets Applet HTTP Web Browser Web Browser The protocol used to transmit and receive all data over the World Wide Web. When you type a URL into your browser, you're actually sending an HTTP request to a Web server for a page of information (that's why URLs all begin with " HTTP1.1, the latest version, is currently undergoing revisions to make it work more efficiently with TCP/IP Web Browser
10
Using JDBC No JDBC data source: a connection is built in Java codes via JDBC driver Steps for using JDBC drivers Load the driver Establish a connection to the database Create a statement Process the statement Loading the driver The directory containing the driver library must be part of the CLASSPATH for the Java compiler and the Java virtual machine The JDBC-ODBC Bridge driver is installed automatically with the Java 2 SDK, Standard Edition, as package sun.jdbc.odbc The Java application calls JDBC classes and interfaces to submit SQL statements and retrieve results. The JDBC API is implemented through the JDBC driver. The JDBC Driver is a set of classes that implement the JDBC interfaces to process JDBC calls and return result sets to a Java application. The database (or data store) stores the data retrieved by the application using the JDBC Driver.
11
Establishing a connection to the database
While there are several ways to load the drivers, the following is one of the most reliable… Class.forName(“nameofdriver”).newInstance() Establishing a connection to the database Create an object that has a connection to the database… Connection Conn = DriverManager.getConnection(“connectionString”); Example: DriverManager.getConnection(“jdbc:mysql: //localhost/db1?user=abc&password=pwd”);
12
Details regarding the JDBC connection string:
“connectionString” has three parts (each part is delimited with a colon) Part 1: jdbc: Part 2: a keyword that identifies the DBMS, e.g., mysql: Part 3: a URL for the database, e.g., //localhost/db1?user=abc&password=pwd Creating a statement A statement is created by instantiating a new Statement object Statement Stmt = Conn.createStatement();
13
Processing the statement
The driver’s API documentation will provide details on what statements are available. However, the core statements are standard Note: a driver’s API is a set of functions that the program may call to receive services Examples (also see the codes): ResultSet RS = Stmt.executeQuery(“select * from tab”); int result = Stmt.executeUpdate(“update tab set name=‘abc’ where id = 1”); Prepared statement and callable statement Used to invoke compiled queries and stored procedures in database Similar to command (but not supported by MySQL)
14
An example of JDBC-ODBC and Java
Build a simple database with Microsoft Access named db1.mdb, and create a table in db1.mdb: named CUSTOMER, which has three fields: CustomerID, Name, AreaCode, PhoneNumber, Street, City, State, and Zip; input some data into the table; save the database in somewhere in the disk, say C:\. 2. Create a data source for db1.mdb: open the “Control Panel” of Windows 2000/XP; From the item “Administrative Tools”, find the icon for “Data Sources (ODBC)”, and then click on the icon, from the window “ODBC Data Source Administrator” click on the tab “System DSN”,
15
An Example (con’t) Add a data source, select “Microsoft access driver” and click OK, enter a name for the data source, “test”; and click the tab “select” and find and select the database we just built, db1.mdb. Press “OK”. Now we have created a data source in our Window environment. Install Java 1.4 or higher on your machine and edit the example in Figure 14-3;
16
Figure 14-3 (modified) import java.io.*; import java.sql.*;
public class GeneralTable { public static void main(String[] args) { if (args.length <1) { System.out.println(Insufficient data provided.”); return; } String varTableName= args[0]; varTableName = varTableName.toUpperCase(); System.out.println("Showing Table " + varTableName); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance(); String connString="jdbc:odbc:test"; Check for at least one parameter Set the variable varTableName to the input table name and convert that name to uppercase. JDBC-ODBC driver is loaded JDBC-ODBC Bridge The Bridge is installed automatically with the Java 2 SDK, Standard Edition, as package sun.jdbc.odbc The Bridge is installed automatically with the Java 2 SDK, Standard Edition, as package sun.jdbc.odbc The Bridge driver uses the odbc subprotocol. URLs for this subprotocol are of the form: jdbc:odbc:<data-source-name>[;<attribute-name>=<attribute-value>]*
17
System.out.println("Trying connection with "+connString);
Figure 14-3 System.out.println("Trying connection with "+connString); Connection conn = DriverManager.getConnection(connString); Statement stmt = conn.createStatement(); String varSQL = "SELECT * FROM " + varTableName; ResultSet rs = stmt.executeQuery(varSQL); ResultSetMetaData rsMeta = rs.getMetaData(); String varColNames = ""; int varColCount = rsMeta.getColumnCount(); for (int col =1; col <= varColCount; col++) { varColNames = varColNames + rsMeta.getColumnName(col) + " "; } System.out.println(varColNames); while (rs.next()) { for (int col=1; col<=varColCount; col++) { System.out.print(rs.getString(col) + " "); } System.out.println(); rs.close(); conn.close(); catch (Exception e) { e.printStackTrace(); }
18
An example (con’t) Save it in C:\wan\GeneralTable.java
Compile: C:\wan>javac GeneralTable.java Run it: C:\wan>java GeneralTable customer
19
Questions Can JDBC drivers be imported into Java Programs?
20
Figure 14-4 Implement the logic for the View Ridge CustomerInsert procedure in Chapter 7: Accept four parameters: a new customer’s Name, AreaCode, LocalNumber, and the Nationality of all artists in whom the customer maintains an interest.
21
To be transformed into a java bean
import java.io.*; import java.sql.*; public class CustomerInsert { public static void main(String[] args) { if (args.length<4) { System.out.println("insufficient data provided."); return; } String varName = args[0]; String varAreaCode = args[1]; String varLocalNumber= args[2]; String varNationality = args[3]; insertData(varName, varAreaCode, varLocalNumber, varNationality); public static void insertData(String varName, String varAreaCode, String varLocalNumber, String varNationality) { System.out.println("Adding row for " + varName); To be transformed into a java bean
22
try { //load JDBC driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance(); String connString="jdbc:odbc:test"; System.out.println("Trying connection with "+connString); Connection conn = DriverManager.getConnection(connString); Statement stmt = conn.createStatement(); // Now check for duplicated data String varSQL = "SELECT Name "; String varWhere = "FROM CUSTOMER WHERE Name= '"; varWhere = varWhere + varName + "' AND AreaCode = '"; varWhere = varWhere + varAreaCode + "' AND PhoneNumber = '"; varWhere = varWhere + varLocalNumber + "'"; varSQL = varSQL + varWhere; ResultSet rs= stmt.executeQuery(varSQL); while (rs.next()) { // if get here, there is duplicate data System.out.println("Data Duplicates an existing customer. No change Made."); rs.close(); stmt.close(); conn.close(); return; }
23
C:\wan>javac CustomerInsert.java
// OK to insert new data varSQL = "INSERT INTO CUSTOMER (Name, AreaCode, PhoneNumber)"; varSQL = varSQL + " VALUES ('" + varName + "', '"; varSQL = varSQL + varAreaCode + "', '"; varSQL = varSQL + varLocalNumber + "')"; int result = stmt.executeUpdate(varSQL); if (result == 0) { System.out.println("Problem with Insert"); rs.close(); stmt.close(); conn.close(); return; } C:\wan>javac CustomerInsert.java C:\wan>java CustomerInsert bush us C:\wan>java GeneralTable customer
24
Needs in Developing Web Applications
Create simple interactive Web pages separate content generation from presentation take advantage of reusable, portable objects, simplifying the maintenance of Web applications. Support complex web sites that are fully integrated with enterprise-level applications
25
What is JSP? Java Server Pages (JSP) is a technology that lets you mix regular, static HTML with dynamically-generated HTML. JSP lets you create the two parts separately. Here's an example: <html> <%java.util.Date date=new java.util.Date();%> <head> <meat http-equiv="Content-Type" content="text/html; charset=gb2312"> </head> <body> <p><b> Today is: </b></p> <%=date.getYear()+1900%> .<%=date.getMonth()+1%> .<%=date.getDate()%> </body></html>
26
JSP (Java Server Pages)
JSP: providing a means of creating dynamic Web pages using HTTP, XML, and Java JSP only allows for Java coding, ASP only allows for JavaScript or VBScript coding JSP inherits the power and portability of Java Since Java is powerful and platform-independent, so is JSP JSP Specifications are located at:
27
JSP JSP technology separates content generation from presentation and takes advantage of reusable tags and objects, simplifying the maintenance of your web applications. JSP technology provides the scripting ability you need to create simple interactive Web pages, or it scales to support complex web sites that are fully integrated with enterprise class applications.
28
JSP and Servlets JSP are transformed into standard Java code (in particular, Java servelet), then they are compiled into bytecode (just like a regular Java program) Similar to ASP but fundamentally different in underlying technology Machine independent JSP: subclasses of the HttpServlet class Consequently, due to inheritance, you may embed Java code enclosed by <% … %> directly into JSP
29
What are Java Servlets? Servlets are Java technology's answer to CGI programming. They are programs that run on a Web server and build Web pages. Building Web pages on the fly is useful for a number of reasons: The Web page is based on data submitted by the user. For example the results pages from search engines are generated this way, and programs that process orders for e-commerce sites do this as well. The data changes frequently. For example, a weather-report or news headlines page The Web page uses information from corporate databases or other such sources. For example, you would use this for making a Web page at an on-line store that lists current prices and number of items in stock.
30
What are the Advantages of JSP?
JSP vs. Pure Servlets. JSP doesn't give you anything that you couldn't in principle do with a servlet. But it is more convenient to write (and to modify!) regular HTML than to have a zillion println statements that generate the HTML. By separating the look from the content you can put different people on different tasks: your Web page design experts can build the HTML, leaving places for your servlet programmers to insert the dynamic content.
31
JSP vs. JavaScript JavaScript can generate HTML dynamically on the client. This is a useful capability, but only handles situations where the dynamic information is based on the client's environment. With the exception of cookies, HTTP and form submission data is not available to JavaScript. And, since it runs on the client, JavaScript can't access server-side resources like databases, catalogs, pricing information, and the like.
32
Web Server Applications
To run JSP, the Web server must implement: Java servlet 2.1+, and Java Server Pages 1.0+ Apache web server: not support servlets Apache TomCat: implemented the above specifications Apache Tomcat Apache Tomcat: a common Web server application a servlet processor May run in conjunction with Apache (in a production environment) or standalone (in a development environment)
33
C:\Program Files\Apache Software Foundation\Tomcat 5.5\
Download current version of Tomcat from: Install it in: C:\Program Files\Apache Software Foundation\Tomcat 5.5\ Test it: Directory structure \bin \common \webapps \lib … \ROOT …
34
An simple JSP example: test.jsp
<html> <%java.util.Date date=new java.util.Date();%> <head> A Test of JSP </head> <body> <p><b> Welcome! Today is: </b></p> <%=date.getYear()+1900%> . <%=date.getMonth()+1%> . <%=date.getDate()%> </body> </html>
35
An simple JSP example (con’t)
Edit it using an editor, e.g. WordPad. Save it in: C:\Program Files\Apache Software Foundation\Tomcat5.5\webapps\ROOT\test.jsp Start Tomcat: C:\Program Files\Apache Software Foundation\Tomcat5.5\bin\tomcat5 Open a Web browser and go to:
36
Running JSP JSP compilation process: parse, compile, load and execute
JSP Page Request JSP Servlet Current? no Parse JSP and Create Java Source File JSP compilation process: parse, compile, load and execute yes JSP Servlet in Memory? Compile Java Source File yes no Load the JSP servlet Execute the JSP servlet JSP Page Response
37
Figure 14-6: GeneralTable.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> page import="java.sql.*" %> <HTML> <HEAD> <TITLE> Table Display Using JDBC and MySQL</TITLE> <META NAME="author" CONTENT="Oscar LIN"> <META NAME="Keywords" CONTENT="JSP, JDBC, Database Access."> <META NAME="description" CONTENT="an example of displaying a table using JSP."> <LINK REL=STYLESHEET HREF="JSP-Style.css" TYPE="text/css"> </HEAD> <BODY> <H2> Database Access Example</H2> <%String varTableName= request.getParameter("Table"); varTableName = varTableName.toUpperCase(); %> <H3> Showing Data from MySQL Database db1</H3>
38
<% try { // Load JDBC driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance(); String connString="jdbc:odbc:test"; System.out.println("Trying connection with "+connString); Connection conn = DriverManager.getConnection(connString); Statement stmt = conn.createStatement(); String varSQL = "SELECT * FROM " + varTableName; ResultSet rs = stmt.executeQuery(varSQL); ResultSetMetaData rsMeta = rs.getMetaData(); %> <TABLE BORDER=1 BGCOLOR=#ffffff CELLSPACE=5><FONT FACE="Arial" COLOR=#000000> <CAPTION><B> <%=varTableName%> </B></CAPTION></FONT> <THEAD>
39
<TR> <% String varColNames = ""; int varColCount = rsMeta.getColumnCount(); for (int col =1; col <= varColCount; col++) { %> <TH BGCOLOR=#c0c0c0 BORDERCOLOR=# ><FONT SIZE=2 FACE="Arial" COLOR=#000000> <%=rsMeta.getColumnName(col) %> </FONT> </TH> <% }%> </TR> </THEAD> <TBODY> <% while (rs.next()) { %> <TR VALIGN=TOP> <% for (int col=1; col<=varColCount; col++) { %> <TD BORDERCOLOR=#c0c0c0 ><FONT SIZE=2 FACE="Arial" COLOR=#000000 > <%=rs.getString(col) %> <BR> </FONT> </TD> <% } }
40
//clean up rs.close(); stmt.close(); conn.close(); } catch (ClassNotFoundException e) { out.println("Driver Exception " + e); } %> </TR> </TBODY> <TFOOT></TFOOT> </TABLE> </BODY> </HTML> Example: Run it!
41
Java Bean Model 1.
42
JSP invoking Java Classes (Java Beans)
Important and Useful: It separates the tasks of writing program logic from generating HTML; It Reduces the complexity of managing a Web site. Java Bean A properly mannered Java class; A Java class that has three properties: there are no public instance variables; All persistent values xxx are accessed using methods named getxxx and setxxx Bean classes must either have no constructors or it must have one explicitly defined zero-argument constructor
43
An example using Java Bean
Save it into: C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ROOT\WEB-INF\classes\ Compile it: >javac CustomerInsertBean.java We get CustomerInsertBean.class Edit NewCustomer.html Save it into: C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ROOT\ Edit CustomerInsertUsingBean.jsp Save it into C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ROOT\ Start Tomcat C:\Program Files\Apache Software Foundation\Tomcat 5.5\bin\tomcat5
44
An Example using Java Bean and JDBC
JSP: Display the result set retrieved from Table Testinfo in the database db1 Use the Java Bean DBUtil_MySQL.class Java: Load the JDBC driver Set up the connection Get the ResultSet
45
An example using Java Bean and MySQL
// A Java Bean source code: DBUtil_MySQL.java package lin; import java.io.*; import java.sql.*; public class DBUtil_MySQL { // For MySQL String sDBDriver="com.mysql.jdbc.Driver"; String sConnStr="jdbc:mysql://localhost:3307/"+"db1"+"?user=root"; // for MS ACCESS //String sDBDriver="sun.jdbc.odbc.JdbcOdbcDriver"; //String sConnStr="jdbc:odbc:test"; Connection conn = null; ResultSet rs = null; public DBUtil_MySQL() try { //java.sql.DriverManager.registerDriver(); Class.forName(sDBDriver); } catch(java.lang.ClassNotFoundException e) { System.err.println("testJDBC(): " + e.getMessage()); } An example using Java Bean and MySQL It is necessary to use a package, Otherwise something will go wrong.
46
An example using Java Bean and MySQL
public ResultSet executeQuery(String testJDBC) { rs = null; try conn=DriverManager.getConnection(sConnStr); Statement stmt = conn.createStatement(); rs=stmt.executeQuery(testJDBC); } catch(SQLException ex) System.err.println("aq.executeQuery:"+ex.getMessage()); return rs; An example using Java Bean and MySQL Save it in: \webapps\ROOT\WEB-INF\classes\DBUtil_MySQL.java >javac –d \ DBUtil_MySQL.java Copy the file we got from the compilation DBUtil_MySQL.class in C:\lin to C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ROOT\WEB-INF\classes\lin\
47
testDB_MySQL.jsp Save it to: C:\Program Files\
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title> MY FAQ</title> </head> <body> <p><b> This is my name! </b> </p> page language="java" import ="java.sql.*" pageEncoding="gb2312" %> <jsp:useBean id='workM' class="lin.DBUtil_MySQL" /> <jsp:setProperty name="workM" property="*" /> <% ResultSet RS = workM.executeQuery("SELECT * FROM testinfo"); while (RS.next()) { ResultSet rs = workM.executeQuery("SELECT * FROM testinfo"); String str_name, str_gender; out.println("Get data from a database:: "); <p> </p> <% while (rs.next()) { str_name=rs.getString("name"); str_gender = rs.getString("gender"); out.println(" name is: " + str_name); out.println(" gender is: " + str_gender); %> <p> </p> <% } } RS.close(); %> </body> </html> Save it to: C:\Program Files\ Apache Software Foundation \Tomcat 5.5\webapps\ROOT\ Go to:
48
MySQL Downloading MySQL
An open-source DBMS product that runs on Unix, Linux, and Windows Provides quick and efficient query handling Allows you to create users, databases, tables, auto incrementing fields, etc. The MySQL open-source driver may be downloaded from:
49
Get and Install a Recent Version
Download the 4.0 and/or 4.1 versions of the MySQL win32 distribution. Find the downloaded file, unzip it and start the setup program: By referring to Install it to C:\Program Files\mysql40\ Start it: C:\Program Files\mysql40\bin\
50
Limitations Using My SQL
While MySQL is extremely inexpensive and provides many capabilities, it is not as powerful as commercial products, such as Oracle and SQL Server Using My SQL MySQL commands: use, show, describe
51
Using MySQL >mysql –P 3307 –u root mysql >Show databases;
>sHow databases; (OK) >Use db1; >Show tables; >Describe testinfo; >Select * from testinfo; Or >\q Edit sql.txt >bin>mysql –P 3307 –u root mysql <C:\wan\sql.txt
52
Unzip it to get the jar file: mysql-connector-java-3.0.16-ga-bin.jar
The latest version of the driver is MySQL Connector/J (formerly MM.MySQL driver) is a Java driver that converts JDBC calls into the network protocol used by the MySQL database. is a Type 4 JDBC driver and has a complete JDBC feature set that supports the capabilities of MySQL. Download the driver from Unzip it to get the jar file: mysql-connector-java ga-bin.jar copy it to a public place: …\Tomcat 5.5\common\lib\mysql-connector-java ga-bin.jar
53
JDBC connections JDBC connection to MySQL is different from other user connections Same machine: via socket Different machines: via TCP/IP
54
Concurrency control Backup and recovery
A work-around allows you to grant access to the for the specific account The wildcard % states that the database may be accessed from any host Alternatively, you may supply the specific IP address for your local machine –this provides better security Concurrency control Limited support: read/write locks Backup and recovery Limited support: database/table saving, log files
55
Summary JDBC JSP (Java Server Pages) MySQL Questions?
JDBC driver types Java Servlet and Applets JDBC architecture and components Applications of JDBC JSP (Java Server Pages) JSP, Servlets and Apache Tomcat MySQL MySQL and JDBC Connections; Concurrency control, and backup and recovery Questions?
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.