"Java from getting started to giving up" javase introductory article: Practice-Single Dog rental system

Source: Internet
Author: User

Today, we want to play a big!!!

We have revised the single dog system used in the previous array into a database version and used some simple ideas in object-oriented. If you do not know the crossing of this system, please jump to the directory page, and then select the single dog system (array version) first onlookers for five minutes. The function inside is very simple ...


Five minutes later ...

All right, five minutes, let's go. 650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0048.gif "alt=" J_0048.gif "/>

650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M01/04/D7/wKiom1mk32_RKxTSAABqzHxYcxI569.png "width=" 575 " height= "489" alt= "Wkiom1mk32_rkxtsaabqzhxycxi569.png"/>


The function to be completed is as shown, but the implementation of the code has changed dramatically ...

The first step: analysis

Generally do a project, according to different emphases, the whole project will be divided into three parts: interface, functional business implementation, database operations. The content of the specific three-tier architecture, and so on after the JSP time to fine-talk ha.

So first of all, there are three different packages to keep the contents of these three parts.

650) this.width=650; "src=" Https://s5.51cto.com/wyfs02/M00/06/FC/wKiom1nBw36zoZkoAAAdHmQBB9Y622.png "title=" 11. PNG "alt=" Wkiom1nbw36zozkoaaadhmqbb9y622.png "/>

Com.test: The program entry class that contains the main method is placed under this package.

Com.dog.ui: The interface-related class file is placed under this package.

Com.dog.service: The processing of the business logic in the function is placed under this package.

Com.dog.dao: Classes that deal with databases are placed under this package.

The package is ready, let's analyze what classes to create, according to the Order of reference, the UI calls Service,service to invoke DAO, and how does the method between classes and classes pass data? Entity classes are generally used. So we're going to create another entity package that holds all of the entities classes. Project structure such as:

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M00/06/FE/wKiom1nB1FijBbcOAAA0v6B-BV8885.png "title=" 12. PNG "alt=" Wkiom1nb1fijbbcoaaa0v6b-bv8885.png "/>

Yesterday the article talked about the common operation of JDBC into two categories, add, delete, change is the same operation, query is the same operation, so we can write a general operation class (DBManager), the class contains two methods, respectively, to manipulate the data and query data. The final project structure is shown below:

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M02/A5/AF/wKioL1nB1PWwE651AAA4LOLM5Ts743.png "title=" 12. PNG "alt=" Wkiol1nb1pwwe651aaa4lolm5ts743.png "/>

The analysis process is here, and the following goes into the coding link.

Second, the Code

In order of invocation, we first write the entity class in the entity package.

2.1 Dog Class

public class dog {private int did;//number private string nickname;//Nickname private  int gender;//sex private string outdate;//lease date private int state;//status public  Int getdid ()  {return did;} Public void setdid (Int did)  {this.did = did;} Public string getnickname ()  {return nickname;} Public void setnickname (String nickname)  {this.nickname = nickname;} Public int getgender ()  {return gender;} Public void setgender (Int gender)  {if (gender==1 | |  gender==0) {This.gender = gender;} else{this.gender = 1;}} Public string getoutdate ()  {return outdate;} Public void setoutdate (String outdate)  {this.outdate = outdate;} Public int getstate ()  {return state;} Public void setstate (int state)  {if (state==1 | | state==0) {this.state = state;} else{this.state = 0;}}}

Then write the following class of DAO package.

The 2.2 Dbmanager class is a generic operation class with the following code:

public class dbmanage {static connection con = null;static  preparedstatement ps = null;static resultset rs = null;//Connection Mysqlstatic  String driver =  "Com.mysql.jdbc.Driver";static string url =  "JDBC: Mysql://127.0.0.1:3306/singledogdb ";//Create Connection Object Private static connection getconnect () {try { Class.forName (driver); Con = drivermanager.getconnection (URL, "root", "root");//Connect mysql}catch  ( exception e)  {// todo auto-generated catch blocke.printstacktrace ();} Return con;} Returns the ResultSet object (without parameters) after executing the query Public static resultset getresultset (string sql) {con =  getconnect (); try {ps = con.preparestatement (SQL); Rs = ps.executequery ();}  catch  (sqlexception e)  {e.printstacktrace ();} Return rs;} Returns the ResultSet object (with parameters) after executing the query public static resultset getResultSet (string sql,object[] params) {con = getconnect ();try {ps =  Con.preparestatement (SQL);for  (int i = 0; i < params.length; i++)  ps.setobject (I+1, params[i]); Rs = ps.executequery ();}  catch  (sqlexception e)  {e.printstacktrace ();} Return rs;} Perform add, delete, and change operations, returning the number of rows affected Public static int modifyentiy (string sql, object[] params) { Int num = 0;con = getconnect (); try {ps = con.preparestatement (SQL); for   (int i = 0; i < params.length; i++)  {ps.setobject (i+1,  Params[i]);} Num = ps.executeupdate (); CloseAll ();}  catch  (sqlexception e)  {e.printstacktrace ();} Return num;} Close Connection Public static void closeall () {if  (ps != null) {try {ps.close ();p s  = null;}  catch  (sqlexception e) &NBsp {// todo auto-generated catch blocke.printstacktrace ();}} if (con != null) {try {con.close (); con = null;}  catch  (sqlexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}}}

The following mainly uses the Getresultset () method and the Modifyentiy () method.

The 2.3 Dogdao class code is as follows:

public class dogdao {//Search All single dog Public list<dog> findall () {List<Dog>  List = new arraylist<dog> (); string strsql =  "Select did,nickname,gender,date_format ( outdate, '%Y-%m-%d ')   Outdate,state from dogtbl "; Try {resultset rs = dbmanage.getresultset (STRSQL); while  (Rs.next ())  {dog dog = new dog ();d Og.setdid (Rs.getint ("did")); Dog.setnickname (rs.getstring ("nickname"));d Og.setgender (Rs.getint ("Gender"));d Og.setoutdate (Rs.getstring (" Outdate "));d Og.setstate (Rs.getint (" state ")); List.add (dog);}}  catch  (sqlexception e)  {e.printstacktrace ();} Return list;} New Public int insert (Dog dog) {int result = 0; string strsql =  "insert into dogtbl  (did, nickname, gender )  VALUES  (?,  ?, ?) "; O BJECT[]&NBSP;PARAMS&NBSP;=&NBSP;NEW&NBSP;OBJECT[3];p arams[0] = dog.getdid ();p arams[1] = dog.getnickname ();p arams[2] = dog.getgender (); Result = dbmanage.modifyentiy (strsql, params ); return result;} Delete (the value of result:-1. No such dog  0. Delete failed  1. Delete succeeded) Public int delete (int dogid) {Int result  = 0; string strsql =  "select state from dogtbl where did=?"; O BJECT[]&NBSP;PARAMS&NBSP;=&NBSP;NEW&NBSP;OBJECT[1];p arams[0] = dogid;//1. Query for this record Resultset rs  = dbmanage.getresultset (Strsql, params); Try {if (Rs.next ()) {int state =  Rs.getint ("state");//2.  can delete if (state==0) {strsql =  "delete from dogtbl  if it is not loaned Where did=? and state=0 "; result = dbmanage.modifyentiy (strSql, params );}} Else{result = -1;}}  catch  (sqlexception e)  {e.printstacktrace ();} Return result;} Update loan status Public int update (dog d og) {int result = 0; string strsql;//determine the status to update, and update the loan date if (Dog.getstate () ==1) {strsql =  "Update dogtbl set  state=1,outdate=now ()  where did=? ";} else{strsql =  "Update dogtbl set state=0,outdate=null where did=?";} OBJECT[]&NBSP;PARAMS&NBSP;=&NBSP;NEW&NBSP;OBJECT[1];p arams[0] = dog.getdid ();result =  Dbmanage.modifyentiy (strsql, params ); return result;}}

Includes four operations, add, delete, update loan status and date, query all. after all the features are implemented, the small partners can try to write a search function on their own .

Next, write the classes in the service.

2.4 Dogservice Class

public class Dogservice {private Dogdao Dogdao = new Dogdao ();//Data Access object//query all public list<dog> findAll () {return Dogda O.findall ();} Add public int Add (dog dog) {return Dogdao.insert (dog);} Delete public String Delete (int dogid) {string msg = "Delete succeeded! "; int result = Dogdao.delete (Dogid); if (result==-1) {msg =" no such dog ";} else if (result==0) {msg = "The single dog has been rented and has not been returned, cannot be deleted!" ";} return msg;} Loan public int loan (dog dog) {int result = 0;result = Dogdao.update (dog); return result;} Return: is not found and borrowed code, this is the same, the method name is different, convenient for upper-level people call public int repay (dog dog) {int result = 0;result = Dogdao.update (dog); return Result;}}

Then write the class in the UI package

2.5 Face Class

public class face {//  because the input object is required in many ways, it is defined to the outermost and can be used in every method private scanner  Input = new scanner (system.in);//Create a Business logic object private dogservice dogservice =  New dogservice ();//  Displays the main menu Public void mainmenu ()  {system.out.println ("================ ======"); System.out.println ("Welcome to the single dog rental System"); System.out.println ("1. View"); System.out.println ("2. Add"); System.out.println ("3. Delete"); System.out.println ("4. Loan"); System.out.println ("5. return"); System.out.println ("6. Exit"); System.out.println ("======================");//  Note that if the user enters a number other than 1~6, he needs to be re-entered Int num = 6;do  {system.out.print ("Please select:"); Num = input.nextint ();switch  (num)  {case 1:show (); Break;case 2:add (); Break;case 3:delete (); Break;case 4:loan (); Break;case 5:repay (); break; Case 6:system.out.println ("Sir, next time to play Yo!") Break;default:system.out.println ("What I'm typing, I only know 1,2,3,4,5,6!!!.") "); break;}}  while&nBSP; (num > 6 | | &NBSP;NUM&NBSP;&LT;&NBSP;1);} View Public void show ()  {system.out.println ("======================"); System.out.println ("====> View"); System.out.println (); Showdog (); Gomainmenu ();} Added Public void add () {System.out.println ("======================"); System.out.println ("====> add"); System.out.println ();D og dog = new dog (); System.out.print ("Please enter nickname:");d Og.setnickname (Input.next ()); System.out.print ("Please select Gender (0. Female |):");d Og.setgender (Input.nextint ());//Call to Add Method Dogservice.add (dog); System.out.println ("Add complete! "); Gomainmenu ();} Delete Public void delete () {System.out.println ("======================"); System.out.println ("====> delete"); System.out.println (); System.out.print ("Please enter Number:"); Int dogid = input.nextint ();//Call the Delete method System.out.println ( Dogservice.delete (Dogid)); Gomainmenu ();} Loan Public void loan () {System.out.println ("======================"); System.out.println ("====> loan"); System.out.println (); Showdog ();//Show All single dogs (according to the logic should write a find (state) method in the DAO package to query the corresponding records according to the status, but I lazy cancer attack, no way ...) System.out.print ("Please enter Number"), Int no = input.nextint ();//According to the truth, here should first find the corresponding records according to the ID, After judging the loan status in this record and then deciding whether to lend it, but ... the lazy cancer continues to attack ... Dog dog = new dog ();d og.setdid (NO);d og.setstate (1); if (Dogservice.loan (dog) >0) { System.out.println ("Lend a success!") ");} Else{system.out.println ("Loan failed!") ");} Gomainmenu ();} Return Public void repay () {System.out.println ("======================"); System.out.println ("====> return"); System.out.println (); Showdog ();//Show All single dogs (lazy cancer still in the attack ...) System.out.print ("Please enter Number"); Int no = input.nextint ();//lazy cancer continues to attack ... Dog dog = new dog ();d og.setdid (NO);d og.setstate (0); if (Dogservice.repay (dog) >0) { System.out.println ("Return success!") ");} Else{system.out.println ("Return failed! ");} Gomainmenu ();} Return to main Menu Public void gomainmenu () {System.out.print ("Press any key and return to main Menu:"); String in = input.next (); MainMenu ();} /** *  Show All single Dog  */private void showdog ()  {//viewBe careful not to output the empty elements in the array System.out.println ("t \ n nickname \ t gender \ t status \ t loan date"); System.out.println ("==========================================="); List<dog> list = dogservice.findall ();for  (int i = 0; i  < list.size ();  i++)  {dog dog = list.get (i); System.out.println (Dog.getdid () + "\ T" +dog.getnickname () + "\ T" + (Dog.getgender () ==0? " Female ":" Male ")  + " \ T "+ (Dog.getstate () ==0?" Not lent ":" Already lent \ T "+dog.getoutdate ()));} System.out.println ("===========================================");}}

Note that there are some methods in the code comments, if you want to do the full version, you can optimize!!!


Finally, the Main method:

public static void Main (string[] args) {//TODO auto-generated method Stubface face = new Face (); Face.mainmenu ();}

Here, all the code is written and the test process is as follows:

650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M02/07/05/wKiom1nCJVizpNfYAAAOjbhzrL0019.png "style=" float : none; "title=" 11.png "alt=" Wkiom1ncjvizpnfyaaaojbhzrl0019.png "/>

650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M02/A5/B6/wKioL1nCJSWza1hRAAAVG3GDI1s760.png "style=" float : none; "title=" 12.png "alt=" Wkiol1ncjswza1hraaavg3gdi1s760.png "/>

650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M00/07/05/wKiom1nCJVnQ1GfcAAAcDPfPuBM755.png "style=" float : none; "title=" 13.png "alt=" Wkiom1ncjvnq1gfcaaacdpfpubm755.png "/>

650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M00/A5/B6/wKioL1nCJSXQK2fJAAAfcHOi2LA575.png "style=" float : none; "title=" 14.png "alt=" Wkiol1ncjsxqk2fjaaafchoi2la575.png "/>

650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M01/A5/B6/wKioL1nCJSXSunhDAAAOgWy4p0I197.png "style=" float : none; "title=" 15.png "alt=" Wkiol1ncjsxsunhdaaaogwy4p0i197.png "/>

650) this.width=650; "src=" Https://s5.51cto.com/wyfs02/M01/07/05/wKiom1nCJVnwvUEWAAAhG4LOApM274.png "style=" float : none; "title=" 16.png "alt=" Wkiom1ncjvnwvuewaaahg4loapm274.png "/>

650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M01/A5/B6/wKioL1nCJSWAkSvkAAAMaSguaw8190.png "style=" float : none; "title=" 17.png "alt=" Wkiol1ncjswaksvkaaamasguaw8190.png "/>

650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M00/07/05/wKiom1nCJVnxekLhAAAQzRb53-Y170.png "style=" float : none; "title=" 18.png "alt=" Wkiom1ncjvnxeklhaaaqzrb53-y170.png "/>


Today there are many places because of lazy disease attack, so ..., we understand, a complete process, a lot of steps need to be judged, crossing in the small new people, you do not lazy, put the complete code to fill it, after you can go to update the new Moe in front of the Ah! 650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0028.gif "alt=" J_0028.gif "/>


"Software Thinking" blog address: 51CTO , Blog Park  , interested small partners can go to see the relevant other blog posts.



This article is from the "Software Thinking" blog, please be sure to keep this source http://softi.blog.51cto.com/13093971/1967186

"Java from getting started to giving up" javase introductory article: Practice-Single Dog rental system

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.