java.lang.NumberFormatException: For input string: "" while saving to database - java

I want to add new room, I would type the room details, Room Number, Room type, Bed number and Rates into the text fields, when I click save, I get the error java.lang.NumberFormatException: For input string: ""
The error originates from at RoomMang.jButton1ActionPerformed(RoomMang.java:352) which is fetchFromTextF(); function. See Image :
My insert statement using System.out.println (insertquery); looks like this:
insert into roomdetail(room_no,room_type,room_rate,room_bed)values('','','','');
This is how i fetch the data from the textfields:
public void fetchFromTextF(){
rno=rnumber.getText();
rtype=jTextField2.getText();
rrate=Integer.parseInt(jTextField3.getText());
rbed=jTextField4.getText();
}
And this is my save action performed button:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
clearTextF();
enableTextF();
String query = "SELECT * FROM roomdetail where room_no like '" + rnumber.getText() + "';";
smt = con.createStatement();
rs1 = smt.executeQuery(query);
if (!rs1.next()) {
try {
if (evt.getActionCommand().equals("Save")) {
fetchFromTextF();
int code = JOptionPane.showConfirmDialog(this, "Information of Room No." +rno+ " will be added in database.", "Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
if (code == JOptionPane.YES_OPTION) {
String insertquery = "insert into roomdetail(room_no,room_type,room_rate,room_bed)values('" +rno + "','" + rtype + "'," + rrate + ",'" + rbed + "');";
smt = con.createStatement();
int success = smt.executeUpdate(insertquery);
if (success > 0) {
JOptionPane.showMessageDialog(this, "Record Saved");
jButton1.setText("New");
} else {
JOptionPane.showMessageDialog(this, "Problem in Saving. Retry");
}
} else {
}
} else if (evt.getActionCommand().equals("New")) {
clearTextF();
jButton1.setText("Save");
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(this, "Room No. already used, Give another Room No.");
}
} catch (Exception ex) {
}
}

The value in jTextField3 is blank so the below will fail
rrate=Integer.parseInt(jTextField3.getText());
maybe change to
rrate = -1;
if (jTextField3.getText().trim().length() > 0) {
rrate=Integer.parseInt(jTextField3.getText());
}
or simply catch the exception
try {
rrate=Integer.parseInt(jTextField3.getText().trim ());
}
catch (NumberFormatException ex) {
System.err.println (ex);
rrate = -1;
}

Related

Validating AdminNo in Database

I have a textbox that takes in the input and validates whether there is a record in the database. If there is no record, it should display a JOptionPane. However, if i input any random number that is not in the database and press the check button, nothing happens. If i input an adminNo which is in the DB, the check button will work. How do i solve it? I think its more of my logic in the codes which is the problem
JButton btnCheck = new JButton("Check");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String conn = "select instrument, period, adminNo from reservation "
+ "where adminNo = '" + txtAdmin.getText() + "'";
PreparedStatement pst = sqliteConnection.dbConnector().prepareStatement(conn);
ResultSet rs = pst.executeQuery();
while(rs.next()) {
String adminNo = rs.getString("adminNo");
if(txtAdmin.getText().equals(adminNo)){
System.out.println("Admin number from text: " + txtAdmin.getText() + "Admin number from DB: " + adminNo);
lblDisplayMusicalInstrument.setText(rs.getString("instrument"));
lblDisplayDuration.setText(rs.getString("period"));
}else{
JOptionPane.showMessageDialog(null, "Admin not in database");
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
);
Try the following code
JButton btnCheck = new JButton("Check");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int count = 0;
try{
String conn = "select instrument, period, adminNo from reservation "
+ "where adminNo = '" + txtAdmin.getText() + "'";
PreparedStatement pst = sqliteConnection.dbConnector().prepareStatement(conn);
ResultSet rs = pst.executeQuery();
while(rs.next()) {
count++;
String adminNo = rs.getString("adminNo");
if(txtAdmin.getText().equals(adminNo)){
System.out.println("Admin number from text: " + txtAdmin.getText() + "Admin number from DB: " + adminNo);
lblDisplayMusicalInstrument.setText(rs.getString("instrument"));
lblDisplayDuration.setText(rs.getString("period"));
}
}
} catch(Exception e) {
e.printStackTrace();
}
if(count == 0) {
JOptionPane.showMessageDialog(null, "Admin not in database");
}
}
});

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

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.)

trying to tell user they entered the wrong value in java

i can't figure out how to tell the user that there is "no such title found" when they go to search for a title. when i test it and type in a title from the database it shows the correct information:
Game Id: 2
Title: Goldeneye 007
Rating: T
Platform: Nintendo 64
Developer: RockStar
but if i type in random information the output looks like this:
Game Id: 0
Title: asdsdfdfg
Rating: null
Platform: null
Developer: null
i'm using a basic console application in java with mysql i have two layers.
my presentation layer:
private static Games SearchForGame() {
Logic aref = new Logic();
Games g = new Games();
#SuppressWarnings("resource")
Scanner scanline = new Scanner(System.in);
System.out.println("Please enter the name of the game you wish to find:");
g.setTitle(scanline.nextLine());
aref.SearchGame(g);
System.out.println();
System.out.println("Game Id: " + g.getGameId());
System.out.println("Title: " + g.getTitle());
System.out.println("Rating: " + g.getRating());
System.out.println("Platform: " + g.getPlatform());
System.out.println("Developer: " + g.getDeveloper());
return g;
}
and a logic layer
public Games SearchGame(Games g) {
try {
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url+dbName,userName,password);
String sql = "SELECT GameId,Title,Rating,Platform,Developer FROM games WHERE Title=?";
java.sql.PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, g.getTitle());
ResultSet rs = statement.executeQuery();
while(rs.next()){
g.setGameId(rs.getInt("GameId"));
g.setTitle(rs.getString("Title"));
g.setRating(rs.getString("Rating"));
g.setPlatform(rs.getString("Platform"));
g.setDeveloper(rs.getString("Developer"));
}
} catch (Exception e) {
e.printStackTrace();
}
return g;
}
Use an if statement?
if(g.getRating() != null /*or g.getGameId() == 0 or many other things*/) {
System.out.println();
System.out.println("Game Id: " + g.getGameId());
System.out.println("Title: " + g.getTitle());
System.out.println("Rating: " + g.getRating());
System.out.println("Platform: " + g.getPlatform());
System.out.println("Developer: " + g.getDeveloper());
} else {
System.out.println();
System.out.println("No such title found");
//throw some sort of exception (and plan to catch it) so that you
//can get out of this method without returning g full of null values
}
return g;
You can do that in many ways, will explain one here.
In SearchGame method use isBeforeFirst() method to check if you have any data at all.
if(!resultSet.isBeforeFirst()){
return null;
}
And in your SearchForGame() if the object is null, display a message.
if(g != null) {
System.out.println();
System.out.println("Game Id: " + g.getGameId());
System.out.println("Title: " + g.getTitle());
System.out.println("Rating: " + g.getRating());
System.out.println("Platform: " + g.getPlatform());
System.out.println("Developer: " + g.getDeveloper());
} else {
System.out.println("No data found");
}
Checking nulls is a bad form of flow control. You should consider a boolean result instead.
if(aref.SearchGame(g)) {
System.out.println();
System.out.println("Game Id: " + g.getGameId());
. . .
else {
System.out.println("No such title found");
}
Then in your logic, just do this:
public boolean SearchGame(Games g) {
boolean found = false;
try {
[your sql select here]
if (rs.next()) {
[access result set]
found = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return found;
}
But an even better way is to return a list of Game instance and then check if that list is empty, like this.
List<Game> SearchGames(String title)
That's a good solid API, and you could use it like this:
List<Game> games = aref.SearchGames(title);
if(games.size() > 0) {
Game g = games.get(0);
System.out.println();
System.out.println("Game Id: " + g.getGameId());
. . .
else {
System.out.println("No such title found");
}
This also allows you to find multiple Games with similar titles if you wanted.

How to make an if-else statement to input a value that is not the field and return "Not Found"

As the title says. I have trouble in Returning a value that says "Not Found",
When i try to input a value that is not in range.
PS: I'm new here so be gentle. hehe
public static void checkStatus(String ID_No) throws SQLException{
try{
ResultSet rs;
String validStatus = "SELECT * FROM validation";
st = connection.createStatement();
rs = st.executeQuery(validStatus);
while(rs.next()){
getStudValid = rs.getString("ID_No");
getValidStatus = rs.getString("Validation");
if (!getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
} else if (getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " You are Enrolled!");
}
}
rs.close();
} catch(SQLException e){
System.out.println("Updated "+ ID_No);
}
}
Take that if-else condition in a method which returns a String "NOT FOUND".
Change
public static void checkStatus(String ID_No) throws SQLException{
to
public static String checkStatus(String ID_No) throws SQLException{
then return a String whether successful or "Not Found"
So, essentially when rs.next holds, then that means that there is some sort of value that is found when the query is executed.
RS.next returns a boolean, and using that boolean you can do something like this.
boolean isFound = rs.next();
if(isFound)
{
// your while loop
// at the end of your while loop add isFound = rs.next()
}
else
{
return "Not Found";
}
It depends on what you want to happen when a student is not found here is 2 ways you could do it.
Throw an exception (this would be if it is an error if a student doesnt exist)
try {
checkStatus("studentA");
} catch(StudentNotFoundException e) {
System.out.println("Student wasnt found!");
}
public static void checkStatus(String ID_No) throws SQLException, StudentNotFoundException {
try{
ResultSet rs;
String validStatus = "SELECT * FROM validation";
st = connection.createStatement();
rs = st.executeQuery(validStatus);
while(rs.next()){
getStudValid = rs.getString("ID_No");
getValidStatus = rs.getString("Validation");
if (!getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
return;
} else if (getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " You are Enrolled!");
return;
}
}
throw new StudentNotFoundException(); // create this exception eg: class StudentNotFoundException extends Exception
rs.close();
} catch(SQLException e){
System.out.println("Updated "+ ID_No);
}
}
Or you could return a value
int exists = checkStatus("studentA");
if(exists == 0)
System.out.println("Student wasnt found");
public static int checkStatus(String ID_No) throws SQLException{
try{
ResultSet rs;
String validStatus = "SELECT * FROM validation";
st = connection.createStatement();
rs = st.executeQuery(validStatus);
while(rs.next()){
getStudValid = rs.getString("ID_No");
getValidStatus = rs.getString("Validation");
if (!getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
return 1; // found
} else if (getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " You are Enrolled!");
return 1; // found
}
}
return 0; // no student found
rs.close();
} catch(SQLException e){
System.out.println("Updated "+ ID_No);
return -1; // error occured
}
}
You could develop logic like -
boolean found = false;
while(rs.next()){
getStudValid = rs.getString("ID_No");
getValidStatus = rs.getString("Validation");
if(getStudValid.equals(ID_No)){
if(getValidStatus.equals("Accepted"))
System.out.println("Student " + getStudValid + " You are Enrolled!");
else
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
found =true;
}
}
if(!found)
System.out.println("Student "+ID_No+" Not found");
But I'd recommend you to optimize this code by optimizing your query - SELECT * FROM validation where ID_No=? and also use PrepareStatement.
String validStatus = "SELECT * FROM validation where ID_No=?";
pst = connection.prepareStatement(validStatus);
pst.setString(1,Id_No);
rs = pst..executeQuery();
if(rs.next()){
if(getValidStatus.equals("Accepted"))
System.out.println("Student " + getStudValid + " You are Enrolled!");
else
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
}else
System.out.println("Student "+ID_No+" Not found");
Some related topics -
Difference between Statement and PreparedStatement

Error: After end of result set

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

Categories

Resources