尽管 Java Eclipse 连接到 MS Access,但无法使用删除查询删除记录

Cannot Delete a record with an delete query though Java Eclipse connected to MS Access

在 MS Access 中删除记录时出现问题。打印堆栈跟踪时显示此错误 net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.1 用户缺少权限或找不到对象:PHONE 在 net.ucanaccess.jdbc.UcanaccessStatement.executeUpdate(UcanaccessStatement.java:222) 在 thirdTier.GeneralDBAccess.delete(GeneralDBAccess.java:223) 在 secondTier.DataStorage.deleteConfirmed(DataStorage.java:79) 在 firstTier.UserInterface.begin(UserInterface.java:124) 在 firstTier.ItemDriver.main(ItemDriver.java:16) 原因:java.sql.SQLSyntaxErrorException:用户缺乏权限或找不到对象:PHONE 在 org.hsqldb.jdbc.JDBCUtil.sqlException(来源不明) 在 org.hsqldb.jdbc.JDBCUtil.sqlException(来源不明) 在 org.hsqldb.jdbc.JDBCStatement.fetchResult(来源不明) 在 org.hsqldb.jdbc.JDBCStatement.executeUpdate(来源不明) 在 net.ucanaccess.jdbc.ExecuteUpdate.executeWrapped(ExecuteUpdate.java:67) 在 net.ucanaccess.jdbc.AbstractExecute.executeBase(AbstractExecute.java:152) 在 net.ucanaccess.jdbc.ExecuteUpdate.execute(ExecuteUpdate.java:50) 在 net.ucanaccess.jdbc.UcanaccessStatement.executeUpdate(UcanaccessStatement.java:220) ... 还有 4 个 原因:org.hsqldb.HsqlException:用户缺乏权限或找不到对象:PHONE 在 org.hsqldb.error.Error.error(来源不明) 在 org.hsqldb.error.Error.error(来源不明) 在 org.hsqldb.ExpressionColumn.checkColumnsResolved(来源不明) 在 org.hsqldb.ParserDML.compileDeleteStatement(来源不明) 在 org.hsqldb.ParserCommand.compilePart(来源不明) 在 org.hsqldb.ParserCommand.compileStatements(来源不明) 在 org.hsqldb.Session.executeDirectStatement(来源不明) 在 org.hsqldb.Session.execute(来源不明) ... 还有 10 个

我的用户界面

包第一层;

进口javax.swing.JOptionPane;

导入异常。*;

导入java.sql.*;

导入第二层。*;

public class 用户界面{

        public void begin(){

            //create a data storage
            DataStorage product =new DataStorage();

            //display the menu and process phone & simcard
            boolean finished = false;

            // open file before anything else is done
            try {
                ItemWorker.initialize();
                product.getAll();
                JOptionPane.showMessageDialog (null, "\n** Database successfully opened **\n", "Success", JOptionPane.PLAIN_MESSAGE);
            }
            catch (SQLException se){
                JOptionPane.showMessageDialog(null, "\n**** ERROR: Problem opening database ****\n" + se.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
                finished = true;
            }
            catch (ClassNotFoundException cnfe){
                JOptionPane.showMessageDialog(null, "\n** ERROR: Cannot find database **\n", "ERROR", JOptionPane.ERROR_MESSAGE);
                finished = true;
            }
            if (finished){
                JOptionPane.showMessageDialog(null, "\n*** Fatal ERROR - Program Ended ***\n" +
                        "\n*** Please contact you computer services centre ***\n", "ERROR", JOptionPane.ERROR_MESSAGE);
            }else {
                    try {
                        product.sort();
                    }
                    catch (ClassCastException cce){
                        JOptionPane.showMessageDialog (null, "Data not sorted properly", "Sorting Error",  JOptionPane.INFORMATION_MESSAGE);
                    }
            }

            while  (!finished){
                int selection = showMenu();
                switch (selection){

                case 1: try {
                            product.add(addPhone());
                            product.sort();
                        }
                            catch (DuplicateException de){
                                JOptionPane.showMessageDialog (null, "ERROR: Cannot add Phone - key already exists in database!", "ERROR", JOptionPane.ERROR_MESSAGE);
                            }
                            catch (SQLException se){
                                JOptionPane.showMessageDialog (null, "ERROR: Problem with database - cannot add record!", "ERROR", JOptionPane.ERROR_MESSAGE);
                            }
                            break;

                case 2: try {
                        product.add(addSimCard());
                        product.sort();
                        }
                        catch (DuplicateException de){
                            JOptionPane.showMessageDialog (null, "ERROR: Cannot add SimCard - key already exists in database!", "ERROR", JOptionPane.ERROR_MESSAGE);
                        }
                        catch (SQLException se){
                        JOptionPane.showMessageDialog (null, "ERROR: Problem with database - cannot add record!", "ERROR", JOptionPane.ERROR_MESSAGE);
                        }
                        break;


                case 3: String phoneID = JOptionPane.showInputDialog(null, "What is the Phone ID?", "Phone Enquiry", JOptionPane.INFORMATION_MESSAGE);
                        int index = product.find (new Phone (phoneID.trim()));
                        if (index < 0){
                            JOptionPane.showMessageDialog(null, "Phone not Found - please check Item Code", "Not Found", JOptionPane.INFORMATION_MESSAGE);
                        }else {
                            JOptionPane.showMessageDialog(null, "The Phone Details are: \n\n" + product.get(index) + "\n", "Item Details", JOptionPane.PLAIN_MESSAGE);  
                        }
                        break;

                case 4: String simcardID = JOptionPane.showInputDialog(null, "What is the Simcard ID?", "Sim Card Enquiry", JOptionPane.INFORMATION_MESSAGE);
                        int index1 = product.find (new SimCard (simcardID.trim()));
                        if (index1 < 0){
                            JOptionPane.showMessageDialog(null, "Sim Card not Found - please check Item Code", "Not Found", JOptionPane.INFORMATION_MESSAGE);
                        }else {
                            JOptionPane.showMessageDialog(null, "The Phone Details are: \n\n" + product.get(index1) + "\n", "Item Details", JOptionPane.PLAIN_MESSAGE); 
                        }
                        break;

                case 5: phoneID =  JOptionPane.showInputDialog (null, "What is the Item Code?", "Phone Enquiry", JOptionPane.INFORMATION_MESSAGE);
                        try {
                            Phone p = (Phone) product.delete (new Phone (phoneID.trim()));
                            int respone = JOptionPane.showConfirmDialog(null, p + "\nAre you sure want to delete this record?\n", "Confirm Delete?", JOptionPane.YES_NO_OPTION);
                            if (respone == JOptionPane.YES_OPTION){

                        try{
                            product.deleteConfirmed (product.find (p));
                            product.sort();
                        }
                        catch (NotFoundException nfe){
                            JOptionPane.showMessageDialog(null, "Phone not found - please check Item Code", "Not Found", JOptionPane.INFORMATION_MESSAGE);
                        }
                        catch (SQLException se){
                            se.printStackTrace();
                            }
                            }else {
                                JOptionPane.showMessageDialog(null, "The Phone Record has NOT been Deleted", "Not Deleted", JOptionPane.INFORMATION_MESSAGE);
                            }

                        }
                        catch (NotFoundException nfe){
                                JOptionPane.showMessageDialog (null, "Phone not found - please check Item Code", "Not Found", JOptionPane.INFORMATION_MESSAGE);
                        }
                        break;

                case 6: simcardID =  JOptionPane.showInputDialog (null, "What is the Item Code?", "Sim Card Enquiry", JOptionPane.INFORMATION_MESSAGE);
                        try {
                            SimCard s = (SimCard) product.delete (new SimCard (simcardID.trim()));
                            int respone = JOptionPane.showConfirmDialog(null, s + "\nAre you sure want to delete this record?\n", "Confirm Delete?", JOptionPane.YES_NO_OPTION);
                            if (respone == JOptionPane.YES_OPTION){
                                try{
                                    product.deleteConfirmed (product.find (s));
                                    product.sort();
                                }
                                catch (NotFoundException nfe){
                                    JOptionPane.showMessageDialog(null, "Sim Card not found - please check Item Code", "Not Found", JOptionPane.INFORMATION_MESSAGE);
                                }
                                catch (SQLException se){
                                    se.printStackTrace();
                                }
                            }else {
                                JOptionPane.showMessageDialog(null, "The Sim Card Record has NOT been Deleted", "Not Deleted", JOptionPane.INFORMATION_MESSAGE);
                            }

                        }
                        catch (NotFoundException nfe){
                            JOptionPane.showMessageDialog (null, "Sim Card not found - please check Item Code", "Not Found", JOptionPane.INFORMATION_MESSAGE);
                        }
                        break;

                case 7: phoneID = JOptionPane.showInputDialog (null, "What is the Phone's ID code?", "Phone Enquiry", JOptionPane.INFORMATION_MESSAGE);
                        try {
                            Phone p = (Phone) product.update (new Phone (phoneID.trim()));
                            int response = JOptionPane.showConfirmDialog (null, p + "\nAre you sure you wish to update this record?\n", "Confirm Update?", JOptionPane.YES_NO_OPTION);
                            if (response == JOptionPane.YES_OPTION) {
                                try {
                                    product.updateConfirmed (product.find (p));
                                    product.sort(); // updating shouldn't alter the order, but sort it just in case!!
                                } catch (NotFoundException nfe) {
                                    JOptionPane.showMessageDialog (null, "Phone not found - please check Phone's ID code", "Not Found", JOptionPane.INFORMATION_MESSAGE);
                                } catch (SQLException se) {
                                    se.printStackTrace();
                                }
                            } else {
                                // Phone record not updated
                                JOptionPane.showMessageDialog (null, "The Phone Record has NOT been Updated", "Not Updated", JOptionPane.INFORMATION_MESSAGE);
                            }
                        } catch (NotFoundException nfe){
                            JOptionPane.showMessageDialog (null, "Phone not found - please check Phone ID Code", "Not Found", JOptionPane.INFORMATION_MESSAGE);
                        }
                        break;

                case 8: JOptionPane.showMessageDialog (null, "This option is not yet available");
                        break;

                case 9: JOptionPane.showMessageDialog(null, "Displaying the item information ...", "Item List", JOptionPane.PLAIN_MESSAGE);
                        for (int i=0; i<product.size(); i++){
                            JOptionPane.showMessageDialog(null, product.get(i), "Item Details", JOptionPane.PLAIN_MESSAGE);
                        }
                        break;

                case 10: finished = true;
                        try{
                            ItemWorker.terminate();
                            JOptionPane.showMessageDialog(null, "   ** Database successfully closed **", "All OK", JOptionPane.INFORMATION_MESSAGE);
                        }
                        catch (SQLException se){
                            JOptionPane.showMessageDialog(null, "ERROR: Database not closed correctly", "ERROR", JOptionPane.ERROR_MESSAGE);
                        }
                            JOptionPane.showMessageDialog(null, "    *** Program Ended ***\n        Have a nice day!");
                            break;

                    default: JOptionPane.showMessageDialog(null, "\n** Invalid Selection **\n", "ERROR", JOptionPane.ERROR_MESSAGE);
                }//end switch
            }//end while loop
        }//end begin


        public int showMenu(){
            int selection = 0;
            try{
            String stringSelection = JOptionPane.showInputDialog(
                    "******* MENU *******\n\n" +
                            "1. Add a new Phone\n" +
                            "2. Add a new Sim Card\n" +
                            "3. Find Individual Phone's Details\n" +
                            "4. Find Individual Sim Card's Details\n" +
                            "5. Delete a Phone data\n" +
                            "6. Delete a Sim Card data\n" +
                            "7. Update Phone data\n" +
                            "8. Update Sim Card data\n" +
                            "9. Display all Details\n" +
                            "10. Exit Program\n\n" +
                            "Type the number of your selection, and click OK: ");
            selection = Integer.parseInt(stringSelection.trim());
            return selection;
            }
            catch (Exception e){
                selection = 20;
            }
            return selection;
        }// end showMenu()


            public SimCard addSimCard (){
                SimCard s = new SimCard();


                // validate
            String sId = JOptionPane.showInputDialog (null, "What is the Sim Card ID?").trim().toUpperCase();
            s.setSimcardId (sId);   

            String ic = (JOptionPane.showInputDialog(null, "\nWhat is the item code of the product?")).trim().toUpperCase();
            //trim() gets rid of leading & trailing whitesapce
            s.setItemCode (ic);
            //get their item code
            String iCode = extractItemCode (ic);

            String categories = null;
            categories = JOptionPane.showInputDialog (null, "Add category of this " +iCode+ "?").trim();


            int quantity = 0;
                do{ // range - 0 to 99999
                    String stringiQuantity = JOptionPane.showInputDialog (null, "What is the quantity of this "+iCode+ "?");
                    int intQuantity = Integer.parseInt(stringiQuantity);
                    quantity = s.setQuantity ((int)intQuantity);

                    if (quantity <= 0 && quantity > 9999){
                        JOptionPane.showMessageDialog (null, "Error - PhoneNo must be greater than 0 and less than 99999999", "ERROR", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                    while (quantity <= 0 && quantity > 9999);

                double price = 0.0;
                price = Double.parseDouble(JOptionPane.showInputDialog ("What is the price of this "+ic+ "?").trim());



                    String br_String = null;
                    do{//validate input if type in wrong
                        br_String = JOptionPane.showInputDialog ("This " +iCode+ " service provider is (Telstra, Optus, Vodaphone)").trim();
                        if (!br_String.equals ("Telstra") && !br_String.equals("Optus")
                        && !br_String.equals ("Vodaphone")){
                            JOptionPane.showMessageDialog (null, "Error - Sim Card must be Telstra, Optus, Vodaphone", "ERROR", JOptionPane.ERROR_MESSAGE);
                            }
                        }
                    while (!br_String.equals ("Telstra") && !br_String.equals("Optus")
                    && !br_String.equals ("Vodaphone"));


                    String expiryDate = null;
                    expiryDate = JOptionPane.showInputDialog ("When is the expiry date of this " +iCode+ "?").trim();


                    int num = 0;
                        do{
                            String stringiNumber = JOptionPane.showInputDialog ("What is the number of this " +iCode+ "?");
                            int intNum = Integer.parseInt(stringiNumber);
                            num = s.setQuantity ((int)intNum);
                            if (num < 0){
                                JOptionPane.showMessageDialog (null, "Error - value must be 0 or more", "Error", JOptionPane.ERROR_MESSAGE);
                            }
                                                    }
                            while (num < 0);
                        SimCard s1 = new SimCard(ic, categories , (int)quantity, (double)price, br_String, expiryDate, (int)num, sId);
                        return s1;
                }

            public Phone addPhone(){
                Phone p = new Phone();

                // validate what we can as we go
                String pId = JOptionPane.showInputDialog (null, "What is the Phone ID?").trim().toUpperCase();
                p.setPhoneId (pId);

                String ic = (JOptionPane.showInputDialog(null, "\nWhat is the item code of the product?")).trim().toUpperCase();
                //trim() gets rid of leading & trailing whitesapce
                p.setItemCode (ic);
                //get their item code
                String iCode = extractItemCode (ic);

                String categories = null;
                categories = JOptionPane.showInputDialog (null, "Add category of this " +iCode+ "?").trim();


                int quantity = 0;
                    do{ // range - 0 to 9999
                        String stringiQuantity = JOptionPane.showInputDialog (null, "What is the quantity of this "+iCode+ "?");
                        int intQuantity = Integer.parseInt(stringiQuantity);
                        quantity = p.setQuantity ((int)intQuantity);

                        if (quantity <= 0 && quantity > 9999){
                            JOptionPane.showMessageDialog (null, "Error - PhoneNo must be greater than 0 and less than 99999999", "ERROR", JOptionPane.ERROR_MESSAGE);
                            }
                        }
                        while (quantity <= 0 && quantity > 9999);

                    double price = 0.0;
                    price = Double.parseDouble(JOptionPane.showInputDialog ("What is the price of this "+iCode+ "?").trim());


                        String pType = null;
                        do{//validate input if type in wrong
                            pType = JOptionPane.showInputDialog (null, "What is the brand of this " +iCode+ "(Samsung, HTC, Iphone)?").trim();
                            if (!pType.equals ("Samsung") && !pType.equals("Iphone")
                            && !pType.equals ("HTC")){
                                JOptionPane.showMessageDialog (null, "Error - Phone Type must be Samsung, HTC, Iphone", "ERROR", JOptionPane.ERROR_MESSAGE);
                                }
                            }
                        while (!pType.equals ("Samsung") && !pType.equals("Iphone")
                            && !pType.equals ("HTC"));


                        String model =null;
                        model = JOptionPane.showInputDialog ("What is the model of this " +iCode+ "?").trim().toLowerCase();

                            String os = null;
                            do{
                                os = JOptionPane.showInputDialog ("What is the OS of this model in "+iCode+"?").trim();
                                if (!os.equals ("Android") && !os.equals("IOS")
                                && !os.equals ("Windows")){
                                    JOptionPane.showMessageDialog (null, "Error - Phone Type must be Android, IOS, Windows", "Error", JOptionPane.ERROR_MESSAGE);
                                }
                            }
                            while (!os.equals ("Android") && !os.equals("IOS")
                            && !os.equals ("Windows"));

                        Phone hp = new Phone (iCode, categories , (int)quantity, (double)price, pType, model, os, pId);
                        return hp;
                            }

            public String extractItemCode (String sn){

                int index = sn.indexOf(' ');
                String itemsCode;
                if (index !=-1){
                    itemsCode = sn.substring(0,index).trim();
                }
                else{
                    itemsCode = sn;
                }
                return itemsCode;
            }

}

GeneralDBAccess

包第三层;

导入java.sql.*;

进口java.util.ArrayList; // 对于 ArrayList of Objects

导入异常。*;

导入第二层。*;

public class GeneralDBAccess {

    private static Item aItem;
    private static String url;
    private static Connection aConnection;
    private static Statement aStatement;

            // Implement the three static methods ************
            // initialise & terminate - called from PersonWorker
            // getAll - called from DataStorage
    public static void initialize() throws ClassNotFoundException, SQLException{
        // The Data Source Name (DSN) is "persons.accdb"
        url = "jdbc:odbc:MS Access Database;DBQ=.\stocks.accdb";
        // load the jdbc - odbc bridge driver for Windows
        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        // create connection instance
        aConnection = DriverManager.getConnection ("jdbc:ucanaccess://stocks.accdb");
        // create statement object instance for this connection
        aStatement = aConnection.createStatement();
    }

    public static void terminate() throws SQLException{
            //close db connection
            aStatement.close();
            aConnection.close();
    }

    public static ArrayList <Item> getAll() throws SQLException{
        ArrayList <Item> items = new ArrayList<Item>();

        String sqlQuery = "SELECT PhoneID, ItemCode, Categories, Quantity, Price, PhoneType, PhoneModel, OperatingSystem  " +
        "FROM PhoneTable";

        ResultSet rs = aStatement.executeQuery(sqlQuery);
        boolean moreData = rs.next();

        while (moreData){

            String phID = rs.getString(1);
            String itCode = rs.getString(2);
            String category = rs.getString(3);
            int quantity = Integer.parseInt (rs.getString(4));
            double price = Double.parseDouble (rs.getString(5));
            String phoneType = rs.getString(6);
            String phoneModel = rs.getString(7);
            String operatingSystem = rs.getString(8);


            aItem = new Phone (itCode, category , quantity, price, phoneType, phoneModel, operatingSystem, phID);
            items.add (aItem);
            moreData = rs.next();
        }
        sqlQuery = "SELECT SimcardID, ItemCode, Categories, Quantity, Price, SimBrand, ExpiryDate, SimNumber " +
                "FROM SimcardTable";

                rs = aStatement.executeQuery(sqlQuery);
                moreData = rs.next();

                while (moreData) {

                    String siID = rs.getString(1);
                    String itCode = rs.getString(2);
                    String category = rs.getString(3);
                    int quantity = Integer.parseInt (rs.getString(4));
                    double price = Double.parseDouble (rs.getString(5));
                    String scBrand = rs.getString(6);
                    String scExpirydate = rs.getString(7);
                    int scNumber = Integer.parseInt (rs.getString(8));



                    aItem = new SimCard (itCode, category , quantity, price, scBrand, scExpirydate, scNumber, siID);
                    items.add(aItem);
                    moreData = rs.next();
                }
                rs.close();
                return items;
            }



    // Implement the four instance methods *************
                // addNew, delete, update - called from each specific PD class
                // find - used locally by addNew(), delete(), and update().
    private Item find (String objectType, String key) throws NotFoundException, SQLException{
        aItem = null;

        if (objectType.equalsIgnoreCase("Phone")){

            String sqlQuery = "SELECT PhoneID, ItemCode, Categories, Quantity, Price, PhoneType, PhoneModel, OperatingSystem " +
                    "FROM PhoneTable WHERE PhoneID = '"+ key +"'";

            ResultSet rs = aStatement.executeQuery (sqlQuery);

            boolean gotIt = rs.next();
            if (gotIt) {

                String phID = rs.getString(1);
                String itCode = rs.getString(2);
                String category = rs.getString(3);
                int quantity = Integer.parseInt (rs.getString(4));
                double price = Double.parseDouble (rs.getString(5));
                String phoneType = rs.getString(6);
                String phoneModel = rs.getString(7);
                String operatingSystem = rs.getString(8);


                aItem = new Phone (itCode, category , quantity, price, phoneType, phoneModel, operatingSystem, phID);
                rs.close();
            }else{

                rs.close();
                throw (new NotFoundException("not found"));
            }

        }else if (objectType.equalsIgnoreCase("SimCard")){
                    String sqlQuery1 = "SELECT SimcardID, ItemCode, Categories, Quantity, Price, SimBrand, ExpiryDate, SimNumber " +
                            "FROM SimcardTable WHERE SimcardID = '" + key + "'";

            ResultSet rs = aStatement.executeQuery(sqlQuery1);

            boolean gotIt = rs.next();
            if (gotIt){

                String siID = rs.getString(1);
                String itCode = rs.getString(2);
                String category = rs.getString(3);
                int quantity = Integer.parseInt (rs.getString(4));
                double price = Double.parseDouble (rs.getString(5));
                String scBrand = rs.getString(6);
                String scExpirydate = rs.getString(7);
                int scNumber = Integer.parseInt (rs.getString(8));


                aItem = new SimCard (itCode, category , quantity, price, scBrand, scExpirydate, scNumber, siID);
                rs.close();
            }else {

                rs.close();
                throw (new NotFoundException("not found"));
            }

        } 
            return aItem;
    } // end 

    public void addNew (Item aItem) throws DuplicateException, SQLException {
        if (aItem instanceof Phone){
            Phone anPhone = (Phone) aItem;

            String itCode = anPhone.getItemCode();
            String category = anPhone.getCategories();
            String quantity = Integer.toString (anPhone.getQuantity());
            String price = Double.toString (anPhone.getPrice());
            String phoneType = anPhone.getPhoneType();
            String phoneModel = anPhone.getModel();
            String operatingSystem = anPhone.getOperatingSystem();
            String phoneID = anPhone.getPhoneId();



            String sqlInsert = "INSERT INTO PhoneTable (PhoneID, ItemCode, Categories, Quantity, Price, PhoneType, PhoneModel, OperatingSystem)" +
            " VALUES ('" + phoneID +  "', '" + itCode +  "', '" + category + "', '" + quantity + "', '" + price + "', '" + phoneType + "', '" + phoneModel + "', '" + operatingSystem + "')";

            try{
                find ("Phone", phoneID);

                throw (new DuplicateException ("Phone Already Exists in Database"));
            }
            catch (NotFoundException e){

                aStatement.executeUpdate(sqlInsert);
            }
        }else if (aItem instanceof SimCard){
            SimCard anSimCard = (SimCard) aItem;

            String itCode = anSimCard.getItemCode();
            String category = anSimCard.getCategories();
            String quantity = Integer.toString (anSimCard.getQuantity());
            String price = Double.toString (anSimCard.getPrice());
            String scBrand = anSimCard.getBrand();
            String scExpirydate = anSimCard.getExpiryDate();
            String scNumber = Integer.toString (anSimCard.getNumber());
            String simcardID = anSimCard.getSimcardId();

            String sqlInsert = "INSERT INTO SimcardTable (SimcardID, ItemCode, Categories , Quantity, Price, SimBrand, ExpiryDate, SimNumber)" +
            " VALUES ('" + simcardID +  "', '" + itCode +  "', '" + category + "', '" + quantity + "', '" + price + "', '" + scBrand + "', '" + scExpirydate + "', '" + scNumber + "')";

            try{
                find ("SimCard", simcardID);

                throw (new DuplicateException ("SimCard Already Exists in Database"));
            }
            catch (NotFoundException e){

                aStatement.executeUpdate(sqlInsert);
            }
        }
    }

    public void delete (Item aItem) throws NotFoundException, SQLException {
        if (aItem instanceof Phone){
            Phone anPhone = (Phone) aItem;

            String phoneID = anPhone.getPhoneId();

            String sqlDelete = "DELETE FROM PhoneTable "
                                +"WHERE Phone ID = '" + phoneID + "'";


            find ("Phone", phoneID);

            aStatement.executeUpdate(sqlDelete);
        }else if (aItem instanceof SimCard){
            SimCard anSimCard = (SimCard) aItem;

            String simcardID = anSimCard.getSimcardId();

            String sqlDelete = "DELETE FROM SimcardTable " 
                                + "WHERE SimCard ID = '" + simcardID + "'";

            find ("SimCard", simcardID);

            aStatement.executeUpdate(sqlDelete);
        }
    }

    public void update (Item aItem) throws NotFoundException, SQLException {
        if (aItem instanceof Phone) {
            Phone anPhone = (Phone) aItem;

            String itCode = anPhone.getItemCode();
            String category = anPhone.getCategories();
            String quantity = Integer.toString (anPhone.getQuantity());
            String price = Double.toString (anPhone.getPrice());
            String phoneType = anPhone.getPhoneType();
            String phoneModel = anPhone.getModel();
            String operatingSystem = anPhone.getOperatingSystem();
            String phoneID = anPhone.getPhoneId();


            String sqlUpdate = "UPDATE PhoneTable SET ItemCode = '"+ itCode +"', "+  
                                                "Categories = '"+category+"', "+
                                                " Quantity = '"+ quantity + "', " + 
                                                " Price = '" + price +"', "+
                                                " PhoneType = '" + phoneType +"', "+
                                                " PhoneModel = '" + phoneModel +"', "+
                                                " OperatingSystem = '" + operatingSystem +"', "+
                                                " WHERE PhoneID = '" + phoneID + "'";

            find ("Phone", phoneID);

            aStatement.executeUpdate(sqlUpdate);

        }else if (aItem instanceof SimCard){
            SimCard anSimCard = (SimCard) aItem;

            String itCode = anSimCard.getItemCode();
            String category = anSimCard.getCategories();
            String quantity = Integer.toString (anSimCard.getQuantity());
            String price = Double.toString (anSimCard.getPrice());
            String scBrand = anSimCard.getBrand();
            String scExpirydate = anSimCard.getExpiryDate();
            String scNumber = Integer.toString (anSimCard.getNumber());
            String simcardID = anSimCard.getSimcardId();

            String sqlUpdate = "UPDATE SimcardTable SET ItemCode = '"+ itCode +"', "+
                                                "Categories = '"+category+"', "+
                                                " Quantity = '"+ quantity + "', " + 
                                                " Price = '" + price +"', "+
                                                " SimBrand = '" + scBrand +"', "+
                                                " SimExpiryDate = '" + scExpirydate +"', "+
                                                " SimNumber = '" + scNumber +"', "+
                                                " WHERE SimcardID = '" + simcardID + "'";

            find ("SimCard", simcardID);

            aStatement.executeUpdate(sqlUpdate);
        }
    }

}

数据存储

包 secondTier;

导入java.sql.; 导入 java.util.;

导入异常。*;

导入第三层。*;

public class 数据存储{

ArrayListdStore;

public DataStorage(){

    dStore = new ArrayList<Item>();
}


public void getAll() throws SQLException {
    dStore.addAll(GeneralDBAccess.getAll());
}

public void add (Item i) throws SQLException, DuplicateException{
    int index = find (i);
    if (index < 0){
        GeneralDBAccess gdba = new GeneralDBAccess();
        gdba.addNew(i);

        dStore.add(i);
    }else {
        throw new DuplicateException();
    }
}

public Item update (Item i) throws NotFoundException {
    int index = find (i);
    if (index < 0) {
        throw new NotFoundException ();
    } else {
        i = dStore.get (index);
    }
    return i;
}

public void updateConfirmed (int index) throws NotFoundException, SQLException {
    GeneralDBAccess gdba = new GeneralDBAccess();
    gdba.update (dStore.get (index)); // update Device from the database ...
}


public Item delete (Item i) throws NotFoundException {
    int index = find (i);
    if (index < 0){
        throw new NotFoundException ();
    }else {
        i = dStore.get(index);
    }
    return i;
}


public void deleteConfirmed (int index) throws NotFoundException, SQLException{
    GeneralDBAccess gdba = new GeneralDBAccess();
    gdba.delete (dStore.get(index));
    dStore.remove(index);
}

public int find (Item i){
    int index = -1;
    index = Collections.binarySearch(dStore, i);
    return index;
} 

public void sort(){
    Collections.sort (dStore);
}
public int size(){
    return dStore.size();
}

public Item get (int index){
    return dStore.get(index);
}

}

不确定是找不到phone数据还是查询有误? 请帮忙解决这个问题。

这很可能是罪魁祸首:

String sqlDelete = "DELETE FROM PhoneTable "
    +"WHERE Phone ID = '" + phoneID + "'";

您可能应该使用 WHERE [Phone ID] =WHERE PhoneID =WHERE Phone_ID =,具体取决于 [PhoneTable] table 中列的实际名称。

(您还应该使用 PreparedStatement 参数化查询 而不是动态 SQL。)