S517 Lab Database Operation

download S517 Lab Database Operation

of 5

Transcript of S517 Lab Database Operation

  • 7/28/2019 S517 Lab Database Operation

    1/5

    S517 Lab Database Operation

    Task 1: Browse existing DB

    In this task, you will create a Java project (Dynamic Web Project) toconnect MySql database. This project will provide an easy webinterface to search in a database table and return the relevant results.

    First, create a Dynamic Web Project as pervious labs, and then create ajava Servlet class named like DBsearch.Second, you need to import a complied java library for MySql databaseconnection. You can download this Jar file at: mysql-connector-java-5.0.7-bin.jar and save this file in a folder. Then, right click the projectname in the Project Explorer, and choose Properties. As followingdiagram shows, click Java Build Path, select Libraries tab, and clickAdd External JARs button. In the browse window, select thedownloaded Jar file and click OK to continue.

    Meanwhile, you will have to cope and paste this Jar file into the{project folder}/WebContent/WEB-INF/lib folder and this will be usedby Java Servlet. After finish this, you can click the project and press F5to refresh the project content.

  • 7/28/2019 S517 Lab Database Operation

    2/5

    Third, you need to write some code to connect to a test database. Inorder to start, you need to import necessary classes as following:

    import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;import java.sql.ResultSet;

    Then, please past the following code to replace the class code:

    publicclass DBconnect extends HttpServlet {privatestaticfinallongserialVersionUID = 1L;Connection connection;Statement statement = null;

    /*** @see HttpServlet#HttpServlet()*/

    public DBconnect() {

    super(); // TODO Auto-generated constructor stub

    }

    publicvoid connect () throws Exception {Class.forName("org.gjt.mm.mysql.Driver" );

    String url = "jdbc:mysql://rdc04.uits.iu.edu:3264/S517DB" ;String username = "S517";String password = "S517";connection = DriverManager.getConnection (url, username, password);

    statement = connection.createStatement();}

    protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

    // TODO Auto-generated method stubresponse.setContentType( "text/html");java.io.PrintWriter out = response.getWriter();out.println(""); //Start to print HTML pageout.println("DB connection");out.println("Please click this button and get the DB results");//Create a HTML form with post methodout.println("");out.println("");out.println("");out.println("");out.println("");out.println("");

    }

    protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

    //Result pageresponse.setContentType( "text/html");java.io.PrintWriter out = response.getWriter();out.println("");out.println("DB Result");out.println("DB results:");out.println("ID\tFirstname\tLastname\tAge\tGender
    " );

  • 7/28/2019 S517 Lab Database Operation

    3/5

    //Outputtry {

    connect();ResultSet rs = statement.executeQuery("select * from user"); //Select

    all the records from user tablewhile (rs.next()) { //Read each record

    int ID = rs.getInt("ID");

    String firstname = rs.getString("Firstname");String lastname = rs.getString("Lastname");int age = rs.getInt("Age");String gender = rs.getString("gender");out.println(ID + "\t" + firstname + "\t"+ lastname + "\t" + age

    + "\t" + gender + "\t
    ");}rs.close();statement.close();connection.close();

    } catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();

    }

    out.println("");

    }}

    Please focusing on the global variablesConnection connection;Statement statement = null;

    Which can be used for this class for DB connection and DB statement.There is another method you will use later as following:

    publicvoid connect () throws Exception {Class.forName("org.gjt.mm.mysql.Driver" );String url = "jdbc:mysql://rdc04.uits.iu.edu:3264/S517DB" ;String username = "S517";String password = "S517";connection = DriverManager.getConnection (url, username, password);

    statement = connection.createStatement();}

    Which tells the DB connection information. The url variable declaresthe remote DB location as jdbc:mysql://rdc04.uits.iu.edu. 3264 is this stringis the port number. S517DB is the database name. Meanwhile,username and password string can be found at the correspondingvariables.

    Read doGet and doPost program carefully, and write down thefunctionality of these functions:

    doGet:_________________________________________________________________________________________doPost:_______________________________________________________________________

  • 7/28/2019 S517 Lab Database Operation

    4/5

    _____________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

    Tips: in doPost method, ResultSet rs = statement.executeQuery("select * from user");will open the following table and save all the records into the variablers (rs saved all the records of user table)

    DBname: S517DB Table name: userID Firstname Lastname Age Gender1 George Ryan 23 M2 Kenneth Armstrong 52 M3 Amy Archer 18 F

    4 Don Anderson 25 M5 Jenny Crawford 26 F6 Virginia Allen 19 F7 Billy Rice 62 M8 James Rostetter 26 M9 Paul Ropp 73 M10 Mary Drexler 32 F11 Jenny Cox 45 F

    Task 2: search user age from DB

    In this task, you will create a Java Servlet class, and this class willprovide a very basic interface. Allow user to input an age, and thesystem will return all the records match this input age. i.e.ResultSet rs = statement.executeQuery("select * from user where age= " + searchage);

    Where searchage is the variable read from user input interface.

    After implement this, think about how to improve this interface? Forinstance, when user cannot find any matched records, system will printa message like Sorry, no result found!

    Pay attention! You need to close the database connection, databasestatement, and database recordset.

    Paste your code here:

  • 7/28/2019 S517 Lab Database Operation

    5/5

    doGet:

    doPost: