Java Database SQL

Published on March 2017 | Categories: Documents | Downloads: 23 | Comments: 0 | Views: 167
of 24
Download PDF   Embed   Report

Comments

Content

 

1

Notes from Note Well Ho Hou use Consultants Thesenote notess are wr writt tte en by Well H ouseC onsultants nsultants anddistr striibuted uted unde und er their Open Tr Trai aini ning ng No Note tess Li License. I f a cco opy of this this lice licenseis not  su  supplie ied d at theend of thesenotes, pleasevisit  isit  http: htt p:// / www.w .we ellllho. ho.ne net/ t/ net/ net/ whcotnl.html hcotnl.html  for details. ils.

Well HouseConsultants Samples

Notes fromWell House Consultants

1

 

Q110

1.1 1.1 We Welll House Consult ultan ants Well House Consultants provides niche training, primarily but not exclusively in Ope Op en Sour Source ceprog programmi ramming ng languag languages. We off offer publ publii c courses at our our tr t rai ning ni ng ce centre nt re and pri pri va vatt e courses coursesat your off of fi ce ces s. We also make make some of our trai ni ning ng note not esava vaii lable ble unde underr our "Ope "Open Trai Traini ning ng Note otes" li ce cense nse, such such as aswe’ we’re doi doing ng i n tthi his sdocument document here.

1.2 1.2 Ope Open n Tr Traini aining ng NotesLi Lice cense With an "Ope Open Training Training Note Notes s Lice License nse", for which hich we make no cha harg rge e, you’re al lowed to t o pri pri nt, nt , useand di di scti ctibut bute e the hes se note not es provide provi ded d tha t hatt you you rre etai n the complete complete and una unaltered lice li cens nse e agreeme reement nt wit with h tthe hem, m, includ includii ng our copyri copyri ght statement ment.. Thi Thi s means that you can learn from the notes, and have others learn from them too. You are NOT allowed to charge (directly or indirectly) for the copying or distribution of these notes, nor are you allowed to charge for presentations making any use of them.

1.3 1. 3 Cour Course ses presented by the author I f yo you u would l i ke us to at attend a course course ((J Java, va, Perl rl,, Pyt Python, PHP, Tcl/ T cl/ Tk, Tk, M MyS ySQL or Linux) Linux) pres presented nted by the author uthor of thes these no note tes s, plea please see our pu pub blic course urse schedule at http:/ htt p:/ / www.w .we ellho.ne ll ho.net/ t/ course ourse/ in inde dex.html x.html If you have a group of 4 or more trainees who require the same course at the same time, it will cost you less to have us run a private course for you. Please visit our onsite training page at http:/ htt p:/ / www.w .we ellho.ne ll ho.net/ t/ course ourse/ otc.html otc.html which will give you details and costing information

1.4 1. 4 Con Contac tactt Detail tails s

Well House Consultants bet found online at htt http:/ p:/ / www.w .we emay llho.ne ll ho.net grah raham@wellh llho o.net li [email protected]

te tec chni nic cal conta ntact admi n nii stratio tion contact

Our full postal address is 404 The Spa Melksham Wiltshire UK SN12 6QL Pho hone ne Fax

2

+44 (0 (0) 1 12 225 70 708225 +44 (0) 1225 707126

Notes fromWell House Consultants

Well House Consultants, Ltd.

 

26

 JRelational  JD DBC – Datab atabas ase Acc cce ess  Ja  Java accesses relatio ion nal databases, such as Orac OracleandMy MyS SQL, through  JDB  JDBC C classes. A manager class which ich overs rse ees theprocess is provide ided with theJava distr striibutio uti on, but you' u'llll alsoneed toobtain tain a dr driver class class to talk to the spe speci ciffic datab databas ase e of your ch cho oice. Usi sing ng MySQ MySQL L as an an e exam xample, this thi s module takes takes you thr thro ough thesour urci cing, ng, confi nfigurati guratio on and useof JDB JD BC so that you can acce access d data ata iin n a re relati lational databasefromwithi within n your Java appli plica catitio on. Prerequisi quisites tes:: I n or order to make themost of thi thiss module, dule, tr trai aine nee es need  prio  p riorr kno knowledgeof Java to an in inttermedia iattelevel and a litt ittlle prior rior kno knowledge of SQL.

Inte Interfa rfac cing ing MySQL tto o JJa ava. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 Using J DB DBC C to a acc cce ess other datab tabases . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 298 98 Using J DBC o on n th the e Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300

 Jav  Java Programming for the Web

JDBC – Relatio ion nal Database Access

295

 

 J811  J81 1

As from Java 1.1, connectivity to relational databases has been provided through JDBC (Java Database Connectivity) in the java.sql package. Note that the Java distribution does not include a full relational database package, nor even the Java classes to access any particular database, which you will need to obtain and install in addition to your J2SE in order to have a Java front-ended relational database. JDBC drivers are not necessarily available for all databases. • Th The ey ar are ava vaii lable ble from var vari ous ve vend ndor ors s for commer commercial da dat abas bases such asAcces Access and Oracle. • Free or i nexpensive nexpensive dat databas bases such as Post ostgreSQL have have lilimi mitted dr dri ve verrs ava vaii lable ble at at present. Basic Techniques: • Reg Regi ster the t he datab databa ase driver driver • Obta Obtain in a Connection object • Use Use a Statement object to send a statement • Retr Retriev ieve e the res results ult s in a ResultSet object These basic techniques (and the java.sql package as a whole) are mostly interfaces rather than classes. The DriverManager  class (a true class, this one!) is responsible for managing all the the cl as asses avai l ab abl e and pro rov vi di ng the the appro rop pri ate ate one fo forr you. The The Class.forName method will register with the DriverManager for you. DriverManager.getConnection will ob obta tain in the connec nnection ob obje jec ct fo forr you; we use a URL of the form:  jdb  jdbc:su :subprotocol:// :/ / host:po :port/ rt/ database SQL

 

Client

Server

Security

 In a web environment, you’ll note that the JDBC connection is made from the clie cli ent usi usi ng a TCP TC P service rvi ce and sockets sockets.. I t fol olllows that the t he specif pecifii c drive dri verr cla cl ass needs needs to be available to the browser and the security aspects of distributing that driver need to be considered. The getConnection()  method takes a user name and password as parameters. You should consider carefully where you obtain and store this information. createStatement() does exactly that – it creates an object with which you can submit queries using either the  executeQuery()   method or for an update the executeUpdate()  method. Queries are formed and sent in SQL (Structured Query Language). Fin ina alllly y, the t he getResultSet()  method retrieves an object of type ResultSet. As ever, get methods allow you to collect data row-by-row or column-by-column. As well as que query rying ing and upda updating ting data data,, fac facili ties ties are availa ilable ble to lea learn about bout the structure of the database. This is know known as Me Meta taDa Data ta;; the DatabaseMetaData int inte erfa rfac ce allow ll ows s you to retrievethisinformationusingthe  getMetaData methodofthe  Connection cl clas ass. Most database accesses will be either to obtain data or to update data, but you can go so far as using  SQL CREATE TABLE  statements to add tables and structure to your database (i.e. you have both the DDL and the DML elements available). Alt Al though most most querie queri es are handle handl ed asone-of one-offfs, each each query bei bei ng commi committted to t o the t he

296

J DBC – Relational DatabaseAccess

Well House Consultants, Ltd.

 

Chapter 2 26 6

data databa base as it is sent, you are able to send que queries ries in sections, tions, for example mple,, atomic tomic transactions which are combined when you commit().

26.1 26. 1 Interfacing MyS MySQL QL to J ava Java int in terfaces ces to data databases through hr ough JD JDBC (Ja (Java Databas Database Connecti Connectivi vitty). Your Your Java Runtime Environment should include the ja  javva.s .sq ql package by default, which is basically a drive driver mana manag ger cla las ss and doe does not not includ include e any drive drivers for for any spec pecific databases. You the th en sour source ce appropr ppr oprii ate dri dri ve verrs from el el sewhere; where; there's there's a li st of suit suitable site:   drivers http::on http / / iSun's ndus ndustr try.j y.jav ava.sun.co a.sun.com/ produc ucts/ ts/jjdbc/ dririve vers which currently lists almost 200 drivers, including several for MySQL. In addition, you could interface MySQL to Java using the JDBC to ODBC bridge but ... don't; you'll be adding in an extra layer of conversions, and the drivers listed on the site above are all "type 4" drivers which means that they're written in native Java code. Here is a complete working example, using drivers sourced via this web site. public class jdbc1 { public static void main(String [] args) {  

java.sql.Connection conn = null;

 

System.out.println("SQL Test");

 

try {

 

Class.forName("org.gjt.mm.mysql.Driver").newInstance();

 

conn = java.sql.DriverManager.getConnection(

  "jdbc:mysql://bhajee/test?user=jtest&password="); } catch (Exception e) {  

System.out.println(e);

 

System.exit(0);

 

}

 

System.out.println("Connection established");

   

try { java.sql.Statement s = conn.createStatement();

 

java.sql.ResultSet r = s.executeQuery ("SELECT code, latitude, longitude FROM dist");

 

while(r.next()) {

 

System.out.println (

 

r.getString("code") + " " +

 

r.getString("latitude") + " " +

 

r.getString("longitude") );

  }

 

catch (Exception e) {

 

System.out.println(e);

 

System.exit(0);

 

}

  }

 Jav  Java Programming for the Web

}

 

}

JDBC – Relatio ion nal Database Access

297

 

 J811  J81 1

And in operation: $ java jdbc1 SQL Test Connection established java.sql.SQLException: General error: Table 'test.dist' doesn't exist $ sql2.pl populate abc123 Table populated from text file $ java jdbc1 SQL Test Connection established AB 3 57.8 AL 0.4 51.7 B 2 52.5 BA 2.4 51.4 BB 2.6 53.8 BD 1.9 53.8 BH 2.9 50.8 (etc) Portugal -8.5 37 Denmark 14 55.5 Germany 9 50 Norway 10.5 59.8 Sweden 18 59 Austria 18 47 Italy 14 42 Italia 14 42 $

26..2 Using JJDBC 26 DBC to access othe otherr databases We've chosen MySQL as our example database for this section since we run it on our training training machines hines, but ju jus st to sho how w you ho how w po porta rtab ble the code is is,, he here re's 's an example that uses the Oracle database: package mypackage1; import java.sql.*; import java.util.*; public class Bruce09 {   public Bruce09()   {   }   public static void main(String[] args)   {  

Connection conn = null;

 

System.out.println("SQL Test");

 

try {

 

DriverManager.registerDriver

 

(new oracle.jdbc.driver.OracleDriver());

 

}

 

catch (Exception e) {

 

System.out.println(e);

   

System.exit(0); }

298

J DBC – Relational DatabaseAccess

Well House Consultants, Ltd.

 

Chapter 2 26 6

 

try {

 

conn = java.sql.DriverManager.getConnection(

 

"jdbc:oracle:thin:username/[email protected]:1234:dbSID");

 

}

 

catch (Exception e) {

 

System.out.println(e);

 

System.exit(0);

 

}

 

System.out.println("Connection established");

 

try {Statement s = conn.createStatement();

 

java.sql.ResultSet r = s.executeQuery

 

("Select display_name from kbi_periods");

 

while(r.next()) {

 

System.out.println (

 

r.getString("display_name") );

 

StringTokenizer Tok = new StringTokenizer(r.getString("display_name"),"-");

 

int n=0;

 

while (Tok.hasMoreElements())

 

System.out.println("" + ++n + ": "+Tok.nextElement());

 

}

 

}

 

catch (Exception e) {

 

System.out.println(e);

 

System.exit(0);

  } } }

The examp xample le extrac xtracts the display_name field field fro from th the e kbi_periods table, and manipulates the data using utility classes such as the string tokenizer. Here's the data description to help you read the example in context: SQL> desc kbi_periods  Name

Null?

Type

 ----------------------------------------- -------- --------------------------- PERIOD_TYPE

VARCHAR2(10)

 PERIOD  PERIOD_START

VARCHAR2(8) DATE

 PERIOD_END

DATE

 DISPLAY_NAME

VARCHAR2(12)

SQL>  

SQL> select * from kbi_periods; PERIOD_TYP PERIOD

PERIOD_ST PERIOD_EN DISPLAY_NAME

---------- -------- --------- --------- -----------MONTH

2002-04

01-APR-02 30-APR-02 APR-02

MONTH

2002-05

01-MAY-02 31-MAY-02 MAY-02

MONTH MONTH

2002-06 2002-07

01-JUN-02 30-JUN-02 JUN-02 01-JUL-02 31-JUL-02 JUL-02

 Jav  Java Programming for the Web

JDBC – Relatio ion nal Database Access

299

 

 J811  J81 1

MONTH

2002-08

01-AUG-02 31-AUG-02 AUG-02

MONTH

2002-09

01-SEP-02 30-SEP-02 SEP-02

MONTH

2002-10

01-OCT-02 31-OCT-02 OCT-02

MONTH

2002-11

01-NOV-02 30-NOV-02 NOV-02

MONTH

2002-12

01-DEC-02 31-DEC-02 DEC-02

MONTH

2003-01

01-JAN-03 31-JAN-03 JAN-03

MONTH

2003-02

01-FEB-03 28-FEB-03 FEB-03

MONTH

2003-03

01-MAR-03 31-MAR-03 MAR-03

12 rows selected. SQL>

26.3 26 .3 Us Usiing J DBC on theWe Web b These days, most users want to access data (including data held in their relational da data tab bases) from a brow rowser, and Java prov provides ides you with tools tools to fa fac cilita ili tate te this. this. For example: • Data i s held in i n a rel relati onal databas database (s (such uch as as MySQL), QL ), which whi ch is is manag manage ed by an appropriate database engine (such as mysqld). • A Ja Java Cla Cl ass, usi usi ng JDBC dri dr i ve verrs, iint nte erface ces s to the the dat databas base engine ngin e al lowing owin g data to be transferred between that class and the database • Th The e Java class i s then re referenced nced by anot another her cla class which whi ch ext exte end the Se Servle rvl et interface • The The Servle rvl et i s acc cce essed by Tomca Tomcatt, which whi ch provide provi des s the JRE conf conformi orming ng to the t he Servlet specification • The The Apache Apache Web Web Se Server rver us use es Tomcat Tomcat to provide provide the Se Servle rvl et capa capabil bil i ty vi vi a an Apache module interface • Th The e use user who want wants s to acc acce ess data in the dat databas base ente nt ers hi his s request on a form for m on his browser, and when he submits the form data is accessed ... Browser -> Apache Server -> Tomcat -> Servlet Class -> JDBC class -> Database Engine -> Database

and then returned to the browser Database -> Database Engine -> JDBC class -> Servlet Class -> Tomcat -> Apache Server -> Browser.

I n order order for f or a scheme cheme such asthi his s to work, work , you ne n eed to t o ha have a number number of resource our ces s other that just your regular Java compiler available: • A Web Web Serv rve er • Java Servl rvle et ca capa pabi billi ty for the we web se server rver • (Your Java envir nvi ronment, onment , but we'l we'lll assume tha that as t hi his s i s a Java course) • • • • • • •

Java vax x classes for ha h andl i ng Servlets and da databas bases, fr f rom the the Ent Ente erpri pri se edit di ti on Appropri ate JDBC drive dri verr clas classes A re r el ati onal onal d da ataba bas se, such such as as MySQL You wi wi l l also nee need tto o have have knowle knowledg dge e of (or acce ccess to) ski skilll s i n: H TML Java SQL This may seem to be a daunting list of topics to learn (as indeed it is if you're new to all of them), but once you have acquired and tuned those skills, and configured and installed the appropriate software, you can write powerful applications quickly and eff ffii ci ently. nt ly. We'll go on and look at two examples that use the mechanism and technologies we've just described to manage single database tables; each shows you a framework structure that you're free to learn from and develop to suit your own needs.

300

J DBC – Relational DatabaseAccess

Well House Consultants, Ltd.

 

Chapter 2 26 6

Example ple: M Mana anagi ging ng atabl table e of iinfor nform mati ation on about a popul opulati ation on This example was written This ritten as a dem demonstra nstration tion for for a client lient who is invo involv lve ed in medic me dica al re res search. rch. His Hi s org orga anisa nisation ti on ne nee eds to ke kee ep rec records which include includes pe peop ople les s’ names, dates dates of birt bi rth, h, and et ethni c backg backgroun round d among amongs st othe otherr i nformati nf ormation, on, so that the t he data can later be analysed and extracted for trend, etc. With an applica plication such uch as this one, ne, there there are usually ually a nu num mber of ta tab bles les and many ma ny fields fields involv involve ed, and the experie perienc nce ed prog programm ramme er will il l write rit e genera nerall cod ode e to avoid much re repe pett i ti on; such codei s, h howe oweve ver, r, ofte oft en ha h ard to fol f olllow as as you're ou're lea learni rn i ng, so this is very much a training example, and you'll find that the code would be longwinded to expand into a complete system [the following example shows you a solutition on to this t his proble problem]. m]. The first file that we'll look at is a piece of pure HTML, and it includes the forms that the t he user start rts s wit with. h. To T o avoid avoid too t oo much code code fragme ragment nta ati on, a si si ngle HTML HTML pa pag ge has forms for both inserting and searching for data from our population table: <html> <head> <title>Servlet to JDBC demo - population for Biomedical research</title> </head> <body bgcolor=white> <h1>Servlet to JDBC demo<BR>Biomedical research - table about a population </h1> Please complete any of the forms on this page to run the demonstration programs that allow data entry and extraction for members of a population who are included in a sample in use for biomedical research <HR> <H2>Enter new data</h2> <form action="http://hawk:8080/nan/servlet/J850insert"><table border=1> <tr><td>Full name of person</td><td><input name=fullname></td></tr> <tr><td>Ethnic Origin</td><td><select name=origin> <option value=Caucasian>Caucasian</option> <option value=Chinese>Chinese</option> <option value="West African">West African</option> <option value=Iranian>Iranian</option> <option value=Indian>Indian</option> <option value=Other>Other</option> </select><br>or enter: <input name=special></td></tr> <tr><td>Date of Birth</td><td><input name=day size=2 value=16> / <input name=month size=2 value=07> / <input name=year size=4 value=1972></td></tr> <tr><td>then ...</td><td><input type=submit value="Enter this data"> </td></tr></table> </form> <HR> <H2>Select data</h2> <form action="http://hawk:8080/nan/servlet/J850select"><table border=1> <tr><td>Name</td><td><input name=name></td></tr> <tr><td>Ethnic Origin</td><td><select name=origin> <option value=Any>Any</option> <option value=Caucasian>Caucasian</option> <option value=Chinese>Chinese</option> <option value="West African">West African</option> <option value=Iranian>Iranian</option> <option value=Indian>Indian</option> </select><br>or enter: <input name=special></td></tr> <tr><td>Year of Birth</td><td><input name=year size=4></td></tr>

 Jav  Java Programming for the Web

JDBC – Relatio ion nal Database Access

301

 

 J811  J81 1

<tr><td>then ...</td><td><input type=submit value="Search for this data"> </td></tr></table></form><hr> </body> </html>

The forms provided both refer to Servlets: J850insert

and

 

J850select

J850insert includes input fields names full name, origin, special, day, month

and year into which the data entry clerk can enter information about a new member being added to the population. J850select includes fewer fields, being the fields on which data can be selected. When the user completes and submits the form, the data is added to the table – we'll look at the code that does this in a minute – and he gets a short report back:

302

J DBC – Relational DatabaseAccess

Figure Figur e 104

What the data entry will appear lliike on the browser.

Figure Figur e 105

The result ulting ing page after the formis filled in.

Well House Consultants, Ltd.

 

Chapter 2 26 6

The J850 insert script is as follows: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /*  * Inserting record into a population table  */ public class J850insert extends HttpServlet {

 

public void doGet(HttpServletRequest request,

 

HttpServletResponse response)

   

throws IOException, ServletException { String called = request.getParameter("fullname"); String origin = request.getParameter("special"); if (origin.equals("")) { origin

= request.getParameter("origin");

} String day = request.getParameter("day"); String month = request.getParameter("month"); String year = request.getParameter("year"); String born = year + "-" + month + "-" + day; // Now do the real work .... String SQLcommand = J850_jdbc.insert(called,origin,born); // After the work is done, send the reply out ....  

response.setContentType("text/html");

 

PrintWriter out = response.getWriter();

 

out.println("<html>");

 

out.println("<head>"); out.println("<title>Thank You</title>");

 

out.println("</head>");

 

out.println("<body bgcolor=\"white\">");

 

out.println("<body>");

 

out.println("<h1>Thank you for adding to our population</h1>"); out.println(called + " has an origin type of " + origin + " and was born " + born+"<BR>"); out.println ("SQL Statement:<BR>"+SQLcommand);

 

out.println("</body>");

 

out.println("</html>");

 

}

}

which is a fairly regular Java Servlet. Just note the call to the static insert method in

 Jav  Java Programming for the Web

JDBC – Relatio ion nal Database Access

303

 

 J811  J81 1

the J850_jdbc 850_jdbc class, to which whi ch the t he Se Servl rvle et haspas passed the t he var vari abl ble e fie fi elds ext xtrracted fr from the form. The J850_jdbc class itself is as follows: public class J850_jdbc { public static String insert(String name, String group, String born) { java.sql.Connection conn = linktodata(); String todo = ("INSERT into population " + "(fullname, ethnicorigin, born) "+ "values ('"+name+"', '"+group+"', '"+born+"')") ; try { java.sql.Statement s = conn.createStatement(); int r = s.executeUpdate (todo); } catch (Exception e) { return ("Oh oops - code 003\n"+e); } return (todo); } public static String select(String name, String group, String yearborn) { java.sql.Connection conn = linktodata(); StringBuffer reply = new StringBuffer("<table border=1>"); StringBuffer conditions = new StringBuffer("where "); if (! group.equals("")) { conditions.append("ethnicorigin = '"+group+"'") ; } if (! name.equals("")) { if (conditions.length() > 6) { conditions.append(" && "); } conditions.append("fullname = '"+name+"'") ; } String selector = null; if (conditions.length() > 6) { selector = conditions.toString(); } else { selector = ""; } String todo = ("SELECT id, fullname, born, ethnicorigin "+ " from population " + selector); try { java.sql.Statement s = conn.createStatement(); java.sql.ResultSet r = s.executeQuery (todo); while(r.next()) { reply.append("<tr>");

304

J DBC – Relational DatabaseAccess

Well House Consultants, Ltd.

 

Chapter 2 26 6

reply.append(tabit(r.getString("id"))); reply.append(tabit(r.getString("ethnicorigin"))); reply.append(tabit(r.getString("fullname"))); reply.append(tabit(r.getString("born"))); reply.append("</tr>"); } reply.append("</table>"); } catch (Exception e) { return ("Oh oops - code 003\n"+e); } return (reply.toString()); } private static String tabit(String box) { return ("<td>"+box+"</td>"); } private static java.sql.Connection linktodata () { java.sql.Connection conn = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); } catch (Exception e) { return conn; // return "Oh dear - code 001 and a quarter"; } try { conn = java.sql.DriverManager.getConnection( "jdbc:mysql://bhajee/J850?user=jtest&password="); } catch (Exception e) { return conn; // return "Oh dear - code 001 and a half"; } return conn; } }

 Jav  Java Programming for the Web

JDBC – Relatio ion nal Database Access

305

 

 J811  J81 1

This code contains the class that uses the JDBC API; to keep the example easy to follow, it's very specific in the information it uses. You'll find that we've hard-coded many items that would be better held in variables such as: fi eld names names Database Tabl ble e name U ser name

(fullname , ethnicorigin  and born) (J850) (Population ) (Jtest)

P sstword wor Haost os serdve verr for database Databas abase engine ngine type

(T (There here password word –) leaky securi curi ty!) localhost (i (impl mpli i citl citi slyno (mysql (mysql))

Since we're going to be making other connections to this same database, we've split out the common code into a priva rivate method thod calle lled d linktodata to avoid code duplication. Our insert method returns the actual SQL command that it used in its call to executeUpdate (used rather than executeQuery, since an Insert operation returns a count of the number of lines affected by the change, rather than data from ta t ables). Agai Agai n, you would not not norma nor mall ly report report ba back ck to your user i n ra r aw SQL, but it demonstrates the mechanisms for trainees "learning the ropes". The ini initt i al form, orm, together wi witt h the t he Java Servle vlet cla classand the Java JDBC acc cce esscla class, provide a complete mechanism for entering data into our simple SQL database; no other user-written files are required. What we haven't yet provided is any mechanism to access the data in our table. Let's look at that; a form has already been provided on the base of our initial HTML page (see Figure 106). Figure Figur e106 A formhas formhasbeen provide provided on thebase of our init initial ial HTML HTM L page

306

J DBC – Relational DatabaseAccess

Well House Consultants, Ltd.

 

Chapter 2 26 6

Completing and submitting this form, we get a thank you page (see Figure 107). Fi Figure gure10 107 7 The thank you pageafter compl pleti eting ng and submitt ttiing the form form.

The only additional file here is the Servlet class J850select, which is called up from the HTM HTML form f orm and provides pr ovidesthe servle rvl et mecha mechani nis sm; it i t cal calls the select met met hod in i n the t he same JDBC referencing class that we used to insert data – although that class has too many constants embedded in it for a real live application, it does at least encapsulate most of that information so that we could change the password or database engine or user name or some other value without the need to start changing other classes too! Here's the source: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /*  * Inserting record into a population table  */ public class J850select extends HttpServlet {

 

public void doGet(HttpServletRequest request,

 

HttpServletResponse response)

   

throws IOException, ServletException { String called = request.getParameter("name"); String origin = request.getParameter("special"); if (origin.equals("")) { origin

= request.getParameter("origin");

} if (origin.equals("Any")) { origin = ""; } String year = request.getParameter("year"); // Now do the real work .... String matches = J850_jdbc.select(called,origin,year); // After the work is done, send the reply out ....  

 Jav  Java Programming for the Web

response.setContentType("text/html");

JDBC – Relatio ion nal Database Access

307

 

 J811  J81 1

 

PrintWriter out = response.getWriter();

 

out.println("<html>");

 

out.println("<head>"); out.println("<title>Thank You</title>");

 

out.println("</head>");

 

out.println("<body bgcolor=\"white\">");

 

out.println("<body>");

 

out.println("<h1>Thank you for viewing our population</h1>"); out.println (matches);

 

out.println("</body>");

 

out.println("</html>");

 

}

}

Once again, this is a straightforward wrapper that calls the JDBC referencing class from within the Servlet. As an an asi asi de, de, you mig mi ght li ke to not n ote e how we've we've writ wri tten our our search mecha mechani nis sm. Us U sers will want to search by name, by year born, or by ethnic group; the where clause of  our SQL request starts off empty (thus calling up all records), but if any entries are made ma de int into the t he se selection cti on form for m bef before it it's submi ubmittted, the t hen n each such such ent entry ry is i s combi combined ned (using an "and" operator so that everything must match) to allow us to become highly selective in the records that are chosen. A final final note note on this example mple:: The examp mple le assume umes that that the data databa bas se and table table already exist when data is first inserted or selected. Creating the table in a live applicat cati on shoul should d be a oneone-off operati operation, on, and you re r eally don't want want t o writ wri te a Servle rvl et jus ustt to do it; much better to use the tools provided with the SQL engine. In our case that means the mysql prog program ram its itse elf. In ord rde er to re rec crea reate an empty ta tab ble befo fore re ne new w courses (and also so that trainees can do this for themselves), we've provided an SQL script file: # make_J850.sql - make up database for Java Servlet to JDBC demo # Data is based on populations for a medical research group. drop database if exists J850; create database J850; use J850; drop table if exists population; create table population ( id

int primary key auto_increment,

fullname

text,

ethnicorigin born

text, date

); # Make up a test record insert into population (fullname, ethnicorigin, born) values ("Graham Ellis", "Caucasian", "1954-07-16");

Exampl ple: e: A more ore general tabl able e management Servl Servlet et We'v We 've e just comple mplete ted d above the study tudy of qu quite ite a long long example mple to sho how w you the mecha mec hanis nisms ms of up upda dating ting and qu que erying rying a spe pec cific ta tab ble le.. Cod Code in that that example is

308

J DBC – Relational DatabaseAccess

Well House Consultants, Ltd.

 

Chapter 2 26 6

repeate repe ted d for each field, field, and the field field na nam mes occur in multiple plac places in the code. Why?Just because that makes it easier to follow for newcomers – for maintenance, it's going to be a nightmare as the code grows. Here's a further example, which is a single servlet class that generates the forms, and also calls both the insert and the select queries. It replaces three files from our prev pre vious example mple,, and furthermo furthermore re it only only include includes one one explicit plicit refe refere renc nce e to each field name making it very easy to change in the future. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /*  * General class for inserting and reporting on a table  */ public class J850staff extends HttpServlet {

 

public void doGet(HttpServletRequest request,

 

HttpServletResponse response)

 

throws IOException, ServletException

 

{ String action = "Unselected"; try { action = request.getParameter("action"); } catch (Exception e) { } if (action == null) action = "Unselected"; String [] fields = {"name","job","office","hometown","title"}; String reply = ""; if (action.equals("Unselected")) { reply = "Hello and Welcome"; } else if (action.startsWith("Insert")) { reply = runInsert(fields,request); } else if (action.startsWith("Select")) { reply = runSelect(fields,request); } else { reply = "Corrupt form"; } reply = reply + "<BR><HR><BR>" + getForms(fields);

 

response.setContentType("text/html");

 

PrintWriter out = response.getWriter();

 

out.println(reply); }

String runInsert (String [] fields,HttpServletRequest request) { StringBuffer fnames = new StringBuffer(""); StringBuffer fvals = new StringBuffer("");

 Jav  Java Programming for the Web

JDBC – Relatio ion nal Database Access

309

 

 J811  J81 1

for (int i=0; i<fields.length; i++) { String called = request.getParameter(fields[i]); if (i>0) fnames.append(", "); fnames.append(fields[i]); if (i>0) fvals.append(", "); fvals.append("'"+called+"'"); } J850sjdbc.insert(fnames.toString(), fvals.toString()); return ("Insertion Done");  

}

String runSelect (String [] fields,HttpServletRequest request) { StringBuffer fselect = new StringBuffer("where "); for (int i=0; i<fields.length; i++) { String called = request.getParameter(fields[i]); if (! called.equals("")) { if (fselect.length() > 6) { fselect.append(" && "); } fselect.append (fields[i] + " = '" + called +"' "); } } if (fselect.length() <= 6) { fselect = new StringBuffer(""); } return (J850sjdbc.select(fields, fselect.toString())); } String getForms (String [] fields) {

StringBuffer insert = new StringBuffer("<table border=1>"); for (int i=0; i<fields.length; i++) { insert.append("<tr><td>"+fields[i]+"</td><td><input name="+ fields[i]+"></td></tr>"); } insert.append("<tr><td>then ..</td><td>"+ "<input type=submit name=action value=Insert>"+ "<input type=submit name=action value=Select>"+ "</td></tr></table>"); return ("<form>"+insert.toString()+"</form>"); } }

310

J DBC – Relational DatabaseAccess

Well House Consultants, Ltd.

 

Chapter 2 26 6

Let's see the form (see Figure 108.) that generates when we first run it (and note the URL is direct to the servlet!). Fi Figure gure 10 108 8 The for form mwhen fi first rst run.

The form here here was gene nera rate ted d by the Servle rvlett itse itself, which hich starts tarts off by chec hecking which submit button was pressed, and if it was neither puts up the welcome form. Should the Insert or Select button be pressed, the resulting action is performed and the result reported prior to the generation of a new form - thus providing a mechanism through which a series of updates and enquiries can be made without having to keep following links back to the form. Figure Fi gure 10 109 9 Result of the compl ple eted form.

 Jav  Java Programming for the Web

JDBC – Relatio ion nal Database Access

311

 

 J811  J81 1

Here's the source code of that class that references the SQL database: public class J850sjdbc { public static String insert(String names, String values) { java.sql.Connection conn = linktodata(); String todo = ("INSERT into staff " + "(" + names + ") values (" + values + ")"); try { java.sql.Statement s = conn.createStatement(); int r = s.executeUpdate (todo); } catch (Exception e) { return ("Oh oops - code 003\n"+e); } return (todo); } public static String select(String [] fields, String selector) { java.sql.Connection conn = linktodata(); StringBuffer reply = new StringBuffer("<table border=1>"); String todo = ("SELECT * "+ " from staff " + selector); try { java.sql.Statement s = conn.createStatement(); java.sql.ResultSet r = s.executeQuery (todo); while(r.next()) { reply.append("<tr>"); for (int i=0;i<fields.length;i++) { reply.append(tabit(r.getString(fields[i]))); } reply.append("</tr>"); } reply.append("</table>"); } catch (Exception e) { return ("Oh oops - code 003\n"+e); } return (reply.toString()); } private static String tabit(String box) { return ("<td>"+box+"</td>"); } private static java.sql.Connection linktodata () {

312

J DBC – Relational DatabaseAccess

Well House Consultants, Ltd.

 

Chapter 2 26 6

java.sql.Connection conn = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); } catch (Exception e) { return conn; // return "Oh dear - code 001 and a quarter"; } try { conn = java.sql.DriverManager.getConnection( "jdbc:mysql://bhajee/J850a?user=jtest&password="); } catch (Exception e) { return conn; // return "Oh dear - code 001 and a half"; } return conn; } }

Perhaps the most major change in this example from the previous one is the use of loops to pass through each field of the database table in turn, collecting the field names in each case from an array of strings that is set up in just a single place in the code.. Note code ote the heavy heavy use use of S Sttri ngBuffe ngBuff ers to buil build up response stri ngs (e.g. (e.g. HTM HTML tables, SQL commands) affecting every field. Although there are many enhancements that can be made to this example, you'll fi nd tha hatt i t provide provi des s at least a st arti rt i ng point point for many many appl applii cat i ons of Java, va, where where you you want wa nt to provide pr ovide an an I nte nt ern rne et-(or i ntrane nt ranett) tot o-da dattaba bas se bridg bri dge e.

Enhanci cing ng our exampl ple es Remember, "Design MATTERS". If you're in at the start of a project, you should give great attention to the overall structure and design of that project and plan to the best of your ability for current and foreseen future requirements from day one, and you should give great consideration to the design before you write even one line of  code. If you jump in to coding on day one without a thorough understanding of your customer's requirement of your work, then you risk both wasting a huge amount of  re res sourc ource es, and prov providing a poor poor or unac unacceptable ptable solution. olution. For larg large er proje projec cts ts,, you may wish to consider using formal design methods such as UML, and design tools such asexamples Rose t o manag manage e your desi desiof gns. gns . course are fit for the purpose for which they Our in this section the were written, which was to illustrate the mechanisms that you may use to interface SQL databases to the Web through Java, but for a production environment there will be many more aspects to consider. Here are a number of pointers and ideas for you to consider. Many of these would be necessary enhancements to our examples were you to wish to use them in a live situation: • Provisi rovisi on of edi ditt and delete delete ca capa pabil bilii ti es. Di D i d you you noti not i ceth tha at once once wehad had ins i nse erte rt ed data into our table, we had no way of removing or correcting it? • Provisi rovisi on of the t he abil bilii ty to handle fi elds of diff di ffe erent ty t ype pes s; our exa example mple was restricted purely to table of textual strings. • Li Limit mitii ng the th e number number of records records report reporte ed bac back and/ and/ or providing providi ng a pa pag gi ng mec mecha ha-nism; while our table remains short, reporting everything is fine ... but if you have a database of several megabytes it would not be. • Reque Reques sti ng conf confii rmation rmati on as as da datt a i s ente nt ered (or updat updated). It I t's ve very ry cleve cleverr of our table to provide a single form for both data entry and selection, but it's almost too clever; it would be very easy indeed for the user to make errors.

 Jav  Java Programming for the Web

JDBC – Relatio ion nal Database Access

313

 

 J811  J81 1

• A mecha mechani nis sm to al all ow diff di ffe erent le l evel vels of acce acces ss to diff dif ferent users, i ncludi ncludi ng a log ogii n capability, passwords, maintenance of state (i.e. Knowing who is who as users move on from one page to the next in a sequence), and also the provision of a mechanism to manage the users. • You may may wi wi sh to consi consi de derr us usii ng the th e JSP inte int erf rfa aceas an altern rna at i veto usi usi ng Se Servle rvl ets di directl rectly, y, es especiall pecially y if your da databas base i s a sma malll par part of a maj major web web s sii t e which whi ch is i s mai mai nta taine ined d by a te tea am using softwa oftware tools tools such uch as Drea Dreamwe mweaver or Frontpa rontpage, and coming from a graphic arts background. • match The The seto lecti ction on mechanism mec hanism hould houl be improve impr oved; d; our asaregular mples expression require requir ed anmatch exa exact ct a field for a record sto be dsupported, whereas might be more appropriate. This could be done using the Apache class (Java prior to 1.4), .4), the built-in uilt-in Regular ular Expres pressions introduc introduce ed in Java 1.4, .4, or the reg regular ular expression capabilities that are available in database engines such as MySQL. You might also wish to provide more advanced search capabilities such as "or" as well as "and", "not", and so on. • The appli applic cati on could could be enhance nhanced d to t o support support multi mult i ple table tables s, and and re r elate them them to one another as data was entered, and also as the data is selected and reported. • Rat Rathe herr t ha han n genera generatti ng the complete complete HTM HTML rre esponse ponse pa pag ge wit withi hin n your Ja Java, va, you mig mi ght wish to to rre ead in i n te t empla mpl ate responsepa pag ges from fi f i les(or from anot another her databas database ta tab ble le)) and then then re repla plac ce markers rkers in those temp templa late tes s wit ith h your our re res sults. ults. This helps helps keep the HTML and Java separate, allowing for easier maintenance, especially if  you have different experts in each of the languages on your staff. • As a fur furtt he herr step step of of gene generali ralis sati on of our example xample,, you you might wish wish to t o hold the t he fi eld names i n a config confi gura urati on fi f i le rat rathe herr tha han n i n the t he Java code code its it self, all owi owi ng the the same applet to be used across a series of applications. As you start to provide enhancements such uch as this (the config file would includ include e tex text descriptions riptions of each field, field, field names, field types), and also standard profiles for the HTML, you're moving away from de dev veloping loping a specifi c app pplilic cation and towa towards a muc much more more exciti xciti ng content management system! Remembe mber: Des Design ign MATTER MATTERS. If you are about to embark on a proje rojec ct which hich uses the facilities described in this section, you need to talk to your user, listen and lea learn about his requ require ireme ments nts,, and con ons sider ider how how which hich of the enhanc nhance ements ments we describe above might apply – and don't be too shocked if they all apply to you!

314

J DBC – Relational DatabaseAccess

Well House Consultants, Ltd.

 

3

License Thesenotes notes ar are di distr striibut ute ed under the Well House Cons Consul ulta tants Open T Tr raini ning ngNotesLicense. Ba  Basi siccally, if you d diistrib stri buteit and and us use eit  for fr fre ee, we’ll let you have it for fr fre ee. I f you charg rge efor its dis isttribu ribution ion of use,, we’ll charge use charge.

Well HouseConsultants Samples

License

9

 

Q111

3.1 3.1 Ope Open n Tr Traini aining ng NotesLi Lice cense Training note Training notes s distribu distribute ted d un unde derr the Well House Consultants nts Open Training NotesLicense(WHCOTNL) may be reproduced for any purpose PROVIDE THAT: • Thi Thi s Lice Li cens nse e statement ment i s retained, unalte unalt ered (sa (save for addit ddi ti ons t o the the cha change ngelog og)) and complete. • No cha charge rgei s made made for the t he di dis str trii bution, buti on, nor for the t he us use e or appli applic cati on thereof. thereof. This Thi s means that youbut canyou usecannot them then to run training sessions or astraining supportsessions. material for those sessions, make a charge for those • Alt Al terations rati ons to the th e content of the document are cl cl earl rly y mark marke ed as as be beii ng such, and and a log of amendments is added below this notice. • The These note not es are provided "as i s" wi wi th no warr warra anty nt y of fi f i tness for purpos pur pose e. Whi Whillst every attempt has been made to ensure their accuracy, no liability can be accepted for any errors of the consequences thereof. Cop Co pyrig right ht is reta retaine ined d by Well Well Hous House Cons Consultants Ltd, Ltd, of 404, The The Spa, MelkMelksham ham, Wiltshire Wiltshire,, UK, SN12 N12 6QL - phone hone num number +44 (1) 1225 708225. Email conta cont act - Gra Gr aham Elli Ell i s (gr (graham@wel wellho.net). ho.net). Ple lea ase send any amendm mendme ents and correc orrecti tions ons to thes these note notes s to the Copy Copyrig ri ght holder - under the spirit of the Open Distribution license, we will incorporate suitable changes into future releases for the use of the community. If you are charged for this material, or for presentation of a course (Other than by Well House Consultants) using this material, please let us know. It is a violation of  the lic lice ense un unde der which hich this no note tes s are distribu distribute ted d fo forr suc uch h a cha harg rge e to be made, except by the Copyright Holder. I f you would li l i ke Well H ouse ouse Consul Consulttants nt st o use use thi his s mat materi al to present a traini rain i ng course for your organisation, or if you wish to attend a public course is one is available le,, ple lea ase contac ntact us or see our web site - http:/ http:/ / www.we .wellho.ne llho.nett - fo forr further further details. Change log Original Version, Well House Consultants, 2004

Updated by: ___________________ on _________________  Updated by: ___________________ on _________________  Updated by: ___________________ on _________________  Updated by: ___________________ on _________________  Updated by: ___________________ on _________________  Updated by: ___________________ on _________________  Updated by: ___________________ on _________________  License Ends.

10

License

Well House Consultants, Ltd.

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close