20 March 2017

JDBC vs Connect SQL Server Insert Update Select Database JAVA

Write an application to allow the user to add or update his/her profile data to the trainees list of the application, details as described below:
-       On entering the application, the application show a menu as below:
1)    Add new account
2)    Update account
3)    Trainee list
-       If user choose add new account option, the user is asked to input account name, password, first-name, last-name, email. Those must not be empty.
-       When valid data are inputted, the user’s profile information would be added or updated into the database. The update occurs only in the case his/her account exists already.
-       When user choose trainee list option, the user would be redirected to the trainee list page which show all the accounts, each account is on a separated row.
-       Any input data validation or application exception must be handled. Warning and error messages must be shown to the user.

Other Requirements:
-       Use Microsoft SQL server as the database.
-       There is not any common defects in the applications
-       Use CheckStyle to specify & fix all the raised error messages


Estimated time: 180 mins
DButil.Java
Java Advanced 2017
package com.demo;

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

public class DButil {

    private static Connection connection = null;

    public static Connection getConnection() {
        if (connection != null) {
            return connection;
        } else {
            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databasename=Employees", "sa", "12345678");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;
        }
    }

    // Test connection database
    public static void main(String[] args) {
        System.out.println(getConnection());
    }

}
Account.Java
Java Advanced  2017
package com.demo;

public class Account {

    private String accName;
    private String password;
    private String firstName;
    private String lastName;
    private String email;

    public String getAccName() {
        return accName;
    }

    public String getPassword() {
        return password;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getEmail() {
        return email;
    }

    public Account(String accName, String password, String firstName,
            String lastName, String email) {
        super();
        this.accName = accName;
        this.password = password;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    public Account() {
        super();
        // TODO Auto-generated constructor stub
    }

}
Menu.Java
Java Advanced 2017
package com.demo;

import java.util.Scanner;

public class Menu {

    Scanner s = new Scanner(System.in);

    // Khoi tao doi tuong logicOption va CheckNull
    LogicOption logicOption = new LogicOption();
    CheckNull checkNull = new CheckNull();

    public void start() {
        while (true) {

            int num = menu();
            switch (num) {
                case 1:
                    System.out.println("#Chose 1");
                    addAccount();
                    break;
                case 2:
                    System.out.println("#Chose 2");
                    updateAccount();
                    break;

                case 3:
                    System.out.println("#Chose 3");
                    displayAccount();
                    break;
                case 4:
                    System.out.println("#Chose 4");
                    System.out.println("Stop the program! Good bye!!");
                    logicOption.closeConnect(); //Dong ket noi
                    System.exit(0); // Thoat vong lap va ket thuc program
                    break;
                default:
                    break;

            }
        }
    }

    private void displayAccount() {
        logicOption.displayAcc(); // Hien thi all
    }

    private void updateAccount() {
        System.out.print("Check update AccName: ");
        String accName = s.nextLine();
        boolean b = logicOption.checkPrimaryKeys(accName); // Check accName
        if (b) {
            System.out.println("=========================================");
            System.out.println("|| Has found Please update this account||");
            System.out.println("=========================================");
            System.out.print("Enter your password: ");
            String password = s.nextLine();
            System.out.print("Enter your first name: ");
            String firstName = s.nextLine();
            System.out.print("Enter your last name: ");
            String lastName = s.nextLine();
            System.out.print("Enter your email: ");
            String email = s.nextLine();

            boolean b1 = checkNull.checkNull(accName, password, firstName, lastName, email);
            if (b1) {
                Account acc = new Account(accName, password, firstName, lastName, email);
                logicOption.updateAccount(acc);
            } else {
                checkNull.showErrorNull(accName, password, firstName, lastName, email, "update");
            }

        } else {
            System.out.println("|||||||||||||||||||||||||||||");
            System.out.println("|| AccName find not found! ||");
            System.out.println("/////////////////////////////");
        }

    }

    private void addAccount() {
        System.out.print("Enter your accName: ");
        String accName = s.nextLine();
        boolean b = logicOption.checkPrimaryKeys(accName); // Check accName
        if (!b) {
            System.out.print("Enter your password: ");
            String password = s.nextLine();
            System.out.print("Enter your first name: ");
            String firstName = s.nextLine();
            System.out.print("Enter your last name: ");
            String lastName = s.nextLine();
            System.out.print("Enter your email: ");
            String email = s.nextLine();

            boolean b1 = checkNull.checkNull(accName, password, firstName, lastName, email);
            if (b1) {
                //True Insert account
                Account acc = new Account(accName, password, firstName, lastName, email);
                logicOption.addAccount(acc); // Them moi account
            } else {
                //show message file null
                checkNull.showErrorNull(accName, password, firstName, lastName, email, "insert");
            }
        } else {
            System.out.println("||||||||||||||||||");
            System.out.println("|| Was existed! ||");
            System.out.println("//////////////////");
        }
    }

    public int menu() {
        System.out.println("1. Add new account");
        System.out.println("2. Update account");
        System.out.println("3. Display Contact");
        System.out.println("4. Exit");
        int num = 0;
        int check = Integer.parseInt(s.nextLine());
        if (check == 1 || check == 2 || check == 3 || check == 4) {
            num = check;
        } else {
            System.out.println("||||||||||||||||||||||");
            System.out.println("|| Xin moi chon lai ||");
            System.out.println("||||||||||||||||||||||");
        }
        return num; // Menu tra ve gia tri 1,2,3,4
    }
}
LogicOption.Java
Java Advanced 2017
package com.demo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Formatter;
import java.util.Scanner;

public class LogicOption {

    private Connection conn = null;
    private PreparedStatement pstmt = null;
    private ResultSet rs;

    Scanner s = new Scanner(System.in);

    public LogicOption() {
        conn = DButil.getConnection();
    }

    public void addAccount(Account account) {

        String insertQuery = "INSERT INTO dbo.account (accName ,password ,firstName,lastName, email) VALUES (?,?,?,?,?)";
        try {
            pstmt = conn.prepareStatement(insertQuery);
            pstmt.setString(1, account.getAccName());
            pstmt.setString(2, account.getPassword());
            pstmt.setString(3, account.getFirstName());
            pstmt.setString(4, account.getLastName());
            pstmt.setString(5, account.getEmail());

            pstmt.executeUpdate();
            System.out.println("Add account success!\n");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateAccount(Account account) {

        String sql = "UPDATE dbo.account SET password = ?, firstName = ?,lastName = ?, email = ?  WHERE accName=?";
        try {
            pstmt = conn.prepareStatement(sql);

            pstmt.setString(1, account.getPassword());
            pstmt.setString(2, account.getFirstName());
            pstmt.setString(3, account.getLastName());
            pstmt.setString(4, account.getEmail());
            pstmt.setString(5, account.getAccName());
            pstmt.executeUpdate();
            System.out.println("Update account success!\n");
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public boolean checkPrimaryKeys(String accName) {
        String sql = "SELECT * FROM dbo.Account Where accName =?";
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, accName);

            rs = pstmt.executeQuery();
            while (rs.next()) {
                String accName1 = rs.getString("accName");
                if (accName1.equalsIgnoreCase(accName)) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public void displayAcc() {
        String sql = "SELECT * FROM dbo.Account";
        Formatter formatter = new Formatter();
        try {
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            System.out.println("-----------------------------------------------------------------");
            System.out.println("AccName || Password || FistName || LastName || Email");
            while (rs.next()) {
                String accName = rs.getString("accName");
                String password = rs.getString("password");
                String firstName = rs.getString("firstName");
                String lastName = rs.getString("lastName");
                String email = rs.getString("email");
                System.out.println(accName + "   " + password + "   " + firstName + "   " + lastName + "    " + email);

            }
            System.out.println("------------------------------------------------------------------");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void closeConnect() {
        try {
            pstmt.close();
            rs.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
CheckNull.Java
Java Advanced 2017
package com.demo;

public class CheckNull {

    public boolean checkNull(String accName, String password, String firstName,
            String lastName, String email) {
        if (accName.length() == 0) {
            return false;
        } else if (accName.length() == 0) {
            return false;
        } else if (password.length() == 0) {
            return false;
        } else if (firstName.length() == 0) {
            return false;
        } else if (lastName.length() == 0) {
            return false;
        } else if (email.length() == 0) {
            return false;
        } else {
            return true;
        }

    }

    public void showErrorNull(String accName, String password,
            String firstName, String lastName, String email, String type) {
        if (accName.length() == 0) {
            System.out.println("===================NULL=====================");
            System.out.println("|| Account Name NULL! Please " + type + " again ||");
            System.out.println("============================================");
        } else if (password.length() == 0) {
            System.out.println("================NULL===================");
            System.out.println("|| Password NULL! Please " + type + " again ||");
            System.out.println("========================================");
        } else if (firstName.length() == 0) {
            System.out.println("==================NULL===================");
            System.out.println("|| First Name NULL! Please " + type + " again ||");
            System.out.println("=========================================");
        } else if (lastName.length() == 0) {
            System.out.println("==================NULL===================");
            System.out.println("|| Last Name NULL! Please " + type + " again ||");
            System.out.println("=========================================");
        } else if (email.length() == 0) {
            System.out.println("=========================================");
            System.out.println("|| Email Name NULL! Please " + type + " again ||");
            System.out.println("==========================================");
        } else {
            System.out.println();
        }

    }
}
Computer.Java
Java Advanced 2017
package com.demo;

public class Computer {

    public static void main(String[] args) {
        Menu menu = new Menu();
        menu.start();
    }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang