Problem with delete record in MS Access. It show this error when print stack trace
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.1 user lacks privilege or object not found: PHONE
at net.ucanaccess.jdbc.UcanaccessStatement.executeUpdate(UcanaccessStatement.java:222)
at thirdTier.GeneralDBAccess.delete(GeneralDBAccess.java:223)
at secondTier.DataStorage.deleteConfirmed(DataStorage.java:79)
at firstTier.UserInterface.begin(UserInterface.java:124)
at firstTier.ItemDriver.main(ItemDriver.java:16)
Caused by: java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: PHONE
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.executeUpdate(Unknown Source)
at net.ucanaccess.jdbc.ExecuteUpdate.executeWrapped(ExecuteUpdate.java:67)
at net.ucanaccess.jdbc.AbstractExecute.executeBase(AbstractExecute.java:152)
at net.ucanaccess.jdbc.ExecuteUpdate.execute(ExecuteUpdate.java:50)
at net.ucanaccess.jdbc.UcanaccessStatement.executeUpdate(UcanaccessStatement.java:220)
... 4 more
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: PHONE
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.ExpressionColumn.checkColumnsResolved(Unknown Source)
at org.hsqldb.ParserDML.compileDeleteStatement(Unknown Source)
at org.hsqldb.ParserCommand.compilePart(Unknown Source)
at org.hsqldb.ParserCommand.compileStatements(Unknown Source)
at org.hsqldb.Session.executeDirectStatement(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
... 10 more
my User interface
package firstTier;
import javax.swing.JOptionPane;
import exceptions.*;
import java.sql.*;
import secondTier.*;
public class UserInterface{
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
package thirdTier;
import java.sql.*;
import java.util.ArrayList; // for ArrayList of Objects
import exceptions.*;
import secondTier.*;
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);
}
}
}
DataStorage
package secondTier;
import java.sql.;
import java.util.;
import exceptions.*;
import thirdTier.*;
public class DataStorage {
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);
}
}
Not sure is cant find the phone data or the query is wrong?
Kindly help on this.
This is most likely the culprit:
String sqlDelete = "DELETE FROM PhoneTable "
+"WHERE Phone ID = '" + phoneID + "'";
You should probably be using either WHERE [Phone ID] =, WHERE PhoneID = or WHERE Phone_ID =, depending on the actual name of the column in the [PhoneTable] table.
(You should also be using a PreparedStatement and a parameterized query instead of dynamic SQL.)
This code to search for a book or a user within databases, there is no problem when you search for a user, but when you search for a book that does not exist, it appears this error:
Error: After end of result set
if(RB1.isSelected()==true)
{
Statement stmt = (Statement)conn.createStatement();
String SQL1 = "select * from usernames";
ResultSet rs1 = stmt.executeQuery(SQL1);
String ID ="";
while(rs1.next())
{
ID = rs1.getString("UserID");
if(UIorBItf.getText().compareTo(ID) == 0)
{
JOptionPane.showMessageDialog(null,rs1.getString("Full_Name") +
" is available","Query result",JOptionPane.INFORMATION_MESSAGE);
break;
}
}
if(UIorBItf.getText().compareTo(ID) != 0)
{
JOptionPane.showMessageDialog(null, UIorBItf.getText() +" is
not available","Query result",JOptionPane.INFORMATION_MESSAGE);
}
}
if(RB2.isSelected()==true)
{
//JOptionPane.showMessageDialog(null, UIorBItf.getText() +" Now
//You are inside Book search","Query result",JOptionPane.INFORMATION_MESSAGE);
Statement stmt2= (Statement)conn.createStatement();
String SQL2 = "select * from books";
ResultSet rs2 = stmt2.executeQuery(SQL2);
String ID ="";
while(rs2.next())
{
ID = rs2.getString("BookID");
if(ID.compareTo(UIorBItf.getText()) ==0)
{
JOptionPane.showMessageDialog(null,rs2.getString("Book_Name") +
" is available","Query result",JOptionPane.INFORMATION_MESSAGE);
break;
}
}
if(UIorBItf.getText().compareTo(ID)!=0)
{
JOptionPane.showMessageDialog(null,rs2.getString("Book_Name") +
" is not available","Query result",JOptionPane.INFORMATION_MESSAGE);
}
}
}catch(Exception e)
{
System.out.println("Error: " + e.getMessage());
}
if(UIorBItf.getText().compareTo(ID)!=0)
{
// problem is here
// from other code I am guessing you want UIorBItf.getText()
// instead of rs2.getString("Book_Name")
JOptionPane.showMessageDialog(null,rs2.getString("Book_Name") +
" is not available","Query result",JOptionPane.INFORMATION_MESSAGE);
}
The problem is here:
if(UIorBItf.getText().compareTo(ID)!=0)
{
JOptionPane.showMessageDialog(null,rs2.getString("Book_Name") +
" is not available","Query result",JOptionPane.INFORMATION_MESSAGE);
}
You can't call rs2.getString("Book_Name") from here, since you only end up here when the while loop is finished. At this point you will already have moved past the last line since rs2.next() has returned false.
You cannot call
rs2.getString("Book_Name")
if rs2.next()
doesnt match anything from your query
select * from books