|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
学习JAVA的目的更多的是培养自身的工作能力,我觉得工作能力的一个核心就是:独立思考能力,因为只有独立思考后,才会有自己的见解servletUpdatingrecordsintheDatabasewithJavaServlets.
Overview:
Thisarticleisnextintheseriesofarticlesaboutselecting,inserting,updatinganddeletingrecordsfromthedatabaseusingJDBC.Inthisarticlewewilllearnhowtoupdaterecordsinthedatabase.IfyouhavefollowedmyearlierarticleaboutInsertingrecordsintheDatabasethenthisarticleisnotgoingtobedifficultatall.90%ofthecodewillbesame.SoifyouhaventreadthatarticlethenIwillsuggestthatyougothroughthatarticlebeforestartingthisoneasquiteafewimportantthingshavebeenexplainedindetailthere.
HowtoUpdateRecords?
ToupdaterecordsinthedatabasewewillbeusingthesamePreparedStatementclassweusedbeforeforinsertingrecords.AlthoughwecanupdaterecordsusingtheStatementclass,theupdateoperationislessefficientandnotoptimizedatall.PreparedStatementfillsthatgapandletsusbuildSQLquerieswhicharecompiledandthusmoreefficient.
PreparedStatement:
ThisclasslikeotherJDBCclasseswehavebeendiscussingispresentinthejava.sqlpackage.ThisishowyougethandleonaPreparedStatementobject:
Stringsql="UPDATENamesSETfirst_name=?,last_name=?WHEREID=?";
//conisConnectionobject
PreparedStatementps=con.prepareStatement(sql);
Connection.prepareStatement()returnsareferencetothePreparedStatementobject.TheonlyargumenttotheConnection.prepareStatement()methodisanSQLstatementcontainingoptional?(questionmark).
Youshouldput?marksinthestatementwhereyouaregoingtoputorchangethevalues,forexampleinmyexampleaboveIplaced?marksatthreeplaceswhereIwillputdifferentvaluesdependingonthevaluesenteredbytheuser.
Sohowtosetthevaluesof?parameters.YousetthevaluesbyusingasetXxx()methodsofPreparedStatementclass.setXxx()areover25methodswhosesyntaxissetObject(intparamIndex,Objecto)whereparamIndexisthenumberof?markfromlefttorightintheSQLstatement.ForexamplewewillusesetString(1,value1)andsetString(2,value2)methodstosetthevalueofbothparameterstotwodifferentvalues.AndsetInt(3,value3)tosetthevalueofthird?marktovalue3.
ps.setString(1,"FirstName");
ps.setString(2,"LastName");
ps.setId(3,1);
ps.executeUpdate();
OncetheparametersaresetinthePreparedStatementobject,weexecutethequeryusingPreparedStatement.executeUpdate()method.YoushouldusePreparedStatement.executeUpdate()forupdate,UPDATEandDELETESQLqueriesandPreparedStatement.executeQuery()foranySQLstatementthatreturnsrecords.
OnthenextpagewemakeuseofPreparedStatementobjecttodevelopauserFormpageinwhichausercanupdatehisfirstandlastnamesandthenwhenhepressesthesubmitbuttontheexistingrecordisupdateedinthedatabaseusingthemethodswejustdiscussed.
UpdateServlet:
CreateanewUpdateServlet.javafileinthe/APP_NAME/WEB-INF/classes/com/stardeveloper/servlets/db/folder.Note/APP_NAME/isthepathofyourapplicationwithinyourapplicationserver,inTomcat4.0/APP_NAME/willbe/CATALINA_HOME/webapps/star/wherestaristhenameoftheapplication.
CopyandpastethefollowingcodeintotheUpdateServlet.javafile:
packagecom.stardeveloper.servlets.db;
importjava.sql.*;
importjava.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
publicclassUpdateServletextendsHttpServlet{
publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)
throwsServletException,IOException{
res.setContentType("text/html");
PrintWriterout=res.getWriter();
out.print("<html><body>");
//connectingtodatabase
Connectioncon=null;
Statementstmt=null;
ResultSetrs=null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:odbc_exmp");
stmt=con.createStatement();
//displayingrecords
rs=stmt.executeQuery("SELECT*FROMNames");
out.print("<formaction="");
out.print(req.getRequestURI());
out.print(""method="post">");
out.print("<inputtype="hidden"name="id"");
out.print("value="0">");
out.print("<inputtype="submit"value="">");
out.print("DisplayRecords<br><br>");
out.print("First&LastNames:<br><br>");
while(rs.next()){
out.print("<formaction="");
out.print(req.getRequestURI());
out.print(""method="post">");
out.print("<inputtype="hidden"");
out.print("name="id"value="");
out.print(rs.getObject(1).toString());
out.print("">");
out.print("<inputtype="text"");
out.print("name="first"value="");
out.print(rs.getObject(2).toString());
out.print("">");
out.print("<inputtype="text"");
out.print("name="last"value="");
out.print(rs.getObject(3).toString());
out.print("">");
out.print("<inputtype="submit"");
out.print("value="">");
out.print("UpdateRecord<br>");
out.print("</form>");
}
}catch(Exceptione){
thrownewServletException(e);
}finally{
try{
if(rs!=null){
rs.close();
rs=null;
}
if(stmt!=null){
stmt.close();
stmt=null;
}
if(con!=null){
con.close();
con=null;
}
}catch(SQLExceptione){}
}
out.print("</pre></code>");
out.print("<p"><ahref="");
out.print(req.getRequestURI());
out.print("">Back</a></p>");
out.print("</body></html>");
out.close();
}
publicvoiddoPost(HttpServletRequestreq,HttpServletResponseres)
throwsServletException,IOException{
res.setContentType("text/html");
PrintWriterout=res.getWriter();
out.print("<html><body>");
out.print("<code><pre>");
out.print("<fontcolor=green>ID ");
out.println("FirstName LastName
</font>");
//receivingparameters
Stringfirst=req.getParameter("first").trim();
Stringlast=req.getParameter("last").trim();
intid;
try{
id=Integer.parseInt(req.getParameter("id").trim());
}catch(NumberFormatExceptione){
thrownewServletException(e);
}
booleanproceed=false;
if(first!=null&&last!=null)
if(first.length()>0&&last.length()>0)
proceed=true;
//connectingtodatabase
Connectioncon=null;
Statementstmt=null;
ResultSetrs=null;
PreparedStatementps=null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:odbc_exmp");
Stringsql="UPDATENamesSETfirst_name=?";
sql+=",last_name=?WHEREID=?";
ps=con.prepareStatement(sql);
stmt=con.createStatement();
//updatingrecords
if(proceed){
ps.setString(1,first);
ps.setString(2,last);
ps.setInt(3,id);
ps.executeUpdate();
}
//displayingrecords
rs=stmt.executeQuery("SELECT*FROMNames");
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print(" ");
out.print(rs.getObject(2).toString());
out.print(" ");
out.print(rs.getObject(3).toString());
out.print("
");
}
}catch(Exceptione){
thrownewServletException(e);
}finally{
try{
if(rs!=null){
rs.close();
rs=null;
}
if(stmt!=null){
stmt.close();
stmt=null;
}
if(ps!=null){
ps.close();
ps=null;
}
if(con!=null){
con.close();
con=null;
}
}catch(SQLExceptione){}
}
out.print("</pre></code>");
out.print("<p"><ahref="");
out.print(req.getRequestURI());
out.print("">Back</a></p>");
out.print("</body></html>");
out.close();
}
}
Startyourapplicationserverandpointyourbrowsertohttp://localhost:8080/star/servlet/com.stardeveloper.servlets.db.UpdateServlettoseetheServletonyourcomputer.Toseethedemopleasemoveontothelastpageofthisarticle.
ForexplanationofUpdateServletcodeabove,pleaseproceedtothenextpage.
Explanation:
NoticethatweareusingthesameAccessdatabasewebuiltintheDisplayingRecordsfromtheDatabasearticlewiththeDSNofodbc_exmp.PleaseconsultthatarticleformoredetailsonthedatabaseandNamestable.
OurUpdateServletclassextendsfromHttpServletclassandoverridestwomethods;doGet()anddoPost().IndoGet()weconnecttothedatabaseandretrieveallthevaluesfromtheNamestableanddisplayaFormtotheuserwithtwoinputfieldscontainingfirstandlastnamesalongwithasubmitbuttonforupdatingrecords.
Stringfirst=req.getParameter("first").trim();
Stringlast=req.getParameter("last").trim();
intid;
try{
id=Integer.parseInt(req.getParameter("id").trim());
}catch(NumberFormatExceptione){
thrownewServletException(e);
}
booleanproceed=false;
if(first!=null&&last!=null)
if(first.length()>0&&last.length()>0)
proceed=true;
IndoPost()weretrievethefirstandlastnamevaluesenteredbytheuserusingHttpServletRequest.getParameter()method.
Usingadoubleifstatementwemakesurethatwearenotenteringnullvaluesintothedatabase.Ifuserhasenteredbothfirstandlastnamethenweproceed.
Connectioncon;
Statementstmt;
ResultSetrs;
PreparedStatementps;
Wedeclaretheobjectswearegoingtousetointeractwiththedatabase.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:odbc_exmp");
WeloadtheSunsJDBC/ODBCdriverandestablishconnectiontoourdatabaseusingtheDSNodbc_exmp.NoticethatthisisthesamedatabaseweusedinDisplayingRecordsfromtheDatabase.PleaseconsultthatarticletoseethestepsofcreatingsuchadatabaseandassigningDSN.
Stringsql="UPDATENamesSETfirst_name=?";
sql+=",last_name=?WHEREID=?";
ps=con.prepareStatement(sql);
stmt=con.createStatement();
WebuildtheSQLstatementwhichwewillusetoinsertrecordsintothedatabase.NextwecreatethePreparedStatementandStatementobjectsusingConnectionobjectsmethods.
if(proceed){
ps.setString(1,first);
ps.setString(2,last);
ps.setInt(3,id);
ps.executeUpdate();
}
Nextwesetthethree?markparametersinourPreparedStatementobjectandupdatetherecordusingPreparedStatement.executeUpdate()method.
rs=stmt.executeQuery("SELECT*FROMNames");
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print(" ");
out.print(rs.getObject(2).toString());
out.print(" ");
out.print(rs.getObject(3).toString());
out.print("
");
}
WecreateourResultSetobjectbyexecutingtheSELECTquery.Wetheniteratethroughtherecordsanddisplayittotheuser.Noticethatthenewrecordwejustinsertedwillalsobevisibletotheuserduringthisiteration.
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(ps!=null)
ps.close();
if(con!=null)
con.close();
Closealltheobjectsthatwecreated.
Ihaventmentionedtry..catchstatementsthatweusedtocatchdifferentexceptionsthatmaybethrownduringopeningandclosingofdatabaseconnection.
OnthenextpageIsumupwhatwelearnedinthisarticle.
Summary:
InthisstepbysteptutorialwelearnedwhatisPreparedStatementclassandhowtouseittobuildfastSQLstatements.WethenmovedforwardtobuildasimpleFormapplicationinwhichwedisplayfirstandlastnamesofalltheusersinourdatabaseallowingausertoupdatehisfirstandlastnameandthesevaluesarethenupdatedinthedatabase.Afterthatallthenamesaredisplayedtouser.Notethatthisapplicationassumesthatyouhavealreadybuilttheodbc_exmp.mdbAccessdatabasewithaDSNofodbc_exmpandcontainsasingletableNameswiththreefieldsID,first_nameandlast_namewhereIDistheprimarykey.TolearnmoreaboutthisdatabasereadDisplayingRecordsfromtheDatabasearticle.
ThedriverweusedwasJDBC/ODBCdriver,thisdrivercomeswithJavaDevelopmentKitsoyoudontneedtodownloadandinstallitseparately.Formoreinformationonhowwebuilttheodbc_exmp.mdbdatabaseandwhataredifferenttypesJDBCdriverspleaseconsulttheabovementionedarticle.
IfyouhavefollowedmyInsertingRecordsintotheDatabasearticlethenyoumusthavenoticedthattheonlyrealchangethatisrequiredtoupdaterecordsinsteadofinsertingistochangetheSQLqueryfromINSERTtoUPDATE,soyouhavegotonlyonelinetochange.
Thatsitforthisarticle.KindlypostyourquestionsintheForum.Thanks.
Thereisnoassociatedmaterialfordownload
Clickheretoseethedemo
先说优点,首先和C,C++这些语言比起来,java很简单,去掉指针的java,非常好理解,自动垃圾回收机制也很好,自从JDK1.5推出以后,性能上又有了很大提高。 |
|