Insert Button Not working after verifying duplicate entry - java

Hi I am beginner I am trying to create a reservation system somehow I can check now if there is duplicate entry however if there's no duplicate entry it is not inserting the data into the database but it if I remove my function to check the duplicate it can insert the data in database. Any suggestion? I am trying to figure it out but it still not working.No error but not adding.
private void btnreserveActionPerformed(java.awt.event.ActionEvent evt) {
try {
DB_Operation DB =new DB_Operation();
String cx1,contactnum11,email1,t11,venuee;
String amount1=aval.getText();
String bal1=b1.getText();
cx1=cx.getText();
contactnum11=contactnum1.getText();
email1=email.getText();
t11=t1.getSelectedItem().toString();
venuee=v.getSelectedItem().toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String Dateee = sdf.format(dad.getSelectedDate().getTime());
boolean unique;
unique = true;
String c1="8am to 12 pm";
String c3="8am to 5pm";
String c2="1pm to 5 pm";
ResultSet rsa= DB.searchQuery("SELECT * FROM `reserve1` WHERE `Date`='"+Dateee+"'");
if ( cx.getText().trim().length() == 0|| contactnum1.getText().trim().length() == 0||email.getText().trim().length() == 0){
final JPanel panel = new JPanel();
JOptionPane.showMessageDialog(panel, "All fields must be completed", "Error", JOptionPane.ERROR_MESSAGE);
}
else if(rsa.isBeforeFirst()){
while(rsa.next()){
if(rsa.getString("Venue").equalsIgnoreCase(venuee)&&
rsa.getString("Date").equalsIgnoreCase(Dateee)&& rsa.getString("Time").equals(t11)){
JOptionPane.showMessageDialog(null,"Duplicate Resevation!");
unique = false;
}
else if((t11.equals(c3))&&(rsa.getString("Venue").equalsIgnoreCase(venuee)&&
rsa.getString("Date").equalsIgnoreCase(Dateee)&& rsa.getString("Time").equals(c1))){
JOptionPane.showMessageDialog(null,"Half Day Resevation Exist!");
unique = false;
}
else if((t11.equals(c3))&&(rsa.getString("Venue").equalsIgnoreCase(venuee)&&
rsa.getString("Date").equalsIgnoreCase(Dateee)&& rsa.getString("Time").equals(c2))){
JOptionPane.showMessageDialog(null,"Half Day Resevation Exist!");
unique = false;
}
else if(unique=true){
try
{
String url="jdbc:mysql://localhost:3306/reservation?zeroDateTimeBehavior=convertToNull";
String userdb="root";
String passdb="";
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection(url,userdb,passdb);
Statement stmt=(Statement)conn.createStatement();
stmt.executeUpdate ("INSERT INTO `reserve1`( `Customer Name`, `Contact Number`, `Email Address`, `Venue`, `Date`, `Time`, `Price`, `Balance`) "+ "VALUES ("+"\""+cx1+"\""+","+"\""+contactnum11+"\""+","+"\""+email1+"\""+","+"\""+venuee+"\""+","+"\""+Date1+"\""+","+"\""+t11+"\""+","+"\""+amount1+"\""+","+"\""+bal1+"\""+")");
JOptionPane.showMessageDialog(null,"Data Added!");
}
catch( HeadlessException | ClassNotFoundException | SQLException e)
{
JOptionPane.showMessageDialog(null, e.getMessage() ,"Error", 1);
}
}
}
}
} catch (SQLException ex) {
Logger.getLogger(reservation.class.getName()).log(Level.SEVERE,
null, ex);
}

I think you should put the if(unique=true) as a separate if statement and not as the part of else if ladder.

Related

Multiply contacts' name On update (ContentProviderOperation)

A very strange porblem. I'm tring to update contacts name by this rule:
- if a contact's name start with "bit" + space ("bit ") so -> update the contact's name to name.substring(4, name.length()), and that means that the contact name will update without the "bit ".
when I use name.substring from number that lower them 4 (I think until the space in contact's name) its working perfectly. When I use from the 4 character onwards the contact's name multiply. For exmaple, when i use name = name.substring(4, name.length()) while name equal to "bit Lili" its update to:
Lili Lili.
private void updateContact(String name) {
ContentResolver cr = getContentResolver();
String where = ContactsContract.Data.DISPLAY_NAME + " = ?";
String[] params = new String[] {name};
Cursor phoneCur = managedQuery(ContactsContract.Data.CONTENT_URI,null,where,params,null);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
if ((null == phoneCur)) {//createContact(name, phone);
Toast.makeText(this, "no contact with this name", Toast.LENGTH_SHORT).show();
return;} else {ops.add(ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name.substring(4,name.length()))
.build());
}
phoneCur.close();
try {cr.applyBatch(ContactsContract.AUTHORITY, ops);}
catch (RemoteException e) {e.printStackTrace();}
catch (OperationApplicationException e) {e.printStackTrace();}}
Thanks!
Not a certain answer but it suppose to work the issue you have is with the
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME //This specific part has a problem with the new update function
,name.substring(4,name.length()))
So my fix proposal is to change it to family name and given name change these as you need based on your question you want to remove the given name so it's a fix for that
public static boolean updateContactName(#NonNull Context context, #NonNull String name) {
if (name.length() < 4) return true;
String givenNameKey = ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME;
String familyNameKey = ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME;
String changedName = name.substring(4, name.length());
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
String where = ContactsContract.Data.DISPLAY_NAME + " = ?";
String[] params = new String[]{name};
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(givenNameKey, changedName)
.withValue(familyNameKey, "")
.build());
try {
context.getContentResolver()
.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

SQLiteException: near "null": syntax error (code 1): , while compiling: create table

Please help me, i get this errors when i run my app use Idea
here is screen of error
http://prntscr.com/en3lcu
here is part of code where create table
private String getTableDDL(final Class<? extends GlassContract.Table> table) {
return getTableDDL(table, GlassContract.getTableName(table));
}
private String getTableDDL(final Class<? extends GlassContract.Table> table, String tableName) {
final StringBuilder sql = new StringBuilder(128);
sql.append("create table ").append(tableName).append(" (");
for (final Field field : table.getFields()) {
if (field.getName().startsWith("_") || field.isAnnotationPresent(Deprecated.class))
continue;
try {
sql.append(field.get(null));
} catch (Exception ignore) {
}
try {
final Field type = table.getDeclaredField("_SQL_" + field.getName() + "_TYPE");
sql.append(' ').append(type.get(null));
} catch (Exception ignore) {
sql.append(" TEXT");
}
sql.append(',');
}
try {
final Field type = table.getDeclaredField("_PK_COMPOSITE");
sql.append("PRIMARY KEY(").append(type.get(null)).append(")");
sql.append(',');
} catch (Exception ignore) {
// ignore
}
try {
final Field type = table.getDeclaredField("_UNIQUE_COMPOSITE");
sql.append("UNIQUE(").append(type.get(null)).append(")");
sql.append(',');
} catch (Exception ignore) {
// ignore
}
sql.setLength(sql.length() - 1); // chop off last comma
sql.append(')');
Log.v(TAG, "DDL for " + table.getSimpleName() + ": " + sql);
return sql.toString();
}
I please help me, because I break my head))
Are you really trying to create text fields in your table that are named null?
Even if this works (and I am not sure it does), you are duplicating this and creating two identically named fields called null
The first field in that CREATE TABLE statement doesn't have a proper name (it is "null"). That's why it blows up.
There's more fields with illegal names as well.

No value specified for parameter Java application with database

I have an application with a list of people and you can change the info of one certain person when you click on a button. So I am trying to update my database but it says that I do not have a value for the 7th parameter, however I do have 7 values. When I print it, it does give me 7 values. It doesn't have a problem with the null (in my if else) because I already tried it without that.
This is my msql
CREATE TABLE Persoon(
persoonId int(3) NOT NULL AUTO_INCREMENT,
leeftijd int(3),
voornaam varchar(40) NOT NULL,
achternaam varchar (40) NOT NULL,
datum date,
locatieId int(3),
filmId int(3) NOT NULL,
PRIMARY KEY (persoonId),
FOREIGN KEY (filmId) references Film(filmId),
FOREIGN KEY (locatieId) references Locatie(locatieId));
My java code
private void btnWijzigenActionPerformed(java.awt.event.ActionEvent evt) {
Object geselecteerdeObject = lstPersonen.getSelectedValue();
Persoon geselecteerdePersoon = (Persoon) geselecteerdeObject;
if(txtLeeftijd.getText() != ""){
try {
String string = txtDatum.getText();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date datumString = format.parse(string);
Persoon nieuwePersoon = new Persoon(geselecteerdePersoon.getPersoonId(),Integer.parseInt(txtLeeftijd.getText()), txtVoornaam.getText(), txtAchternaam.getText(),datumString,geselecteerdePersoon.getLocatieId(),geselecteerdePersoon.getFilmId());
System.out.println("1p "+geselecteerdePersoon.getPersoonId() + " 2p " +Integer.parseInt(txtLeeftijd.getText()) + " 3p "+txtVoornaam.getText() + " 4p " + txtAchternaam.getText() + " 5p " + datumString + " 6p "+ geselecteerdePersoon.getLocatieId()+ " 7p " +geselecteerdePersoon.getFilmId());;
PersoonDao.updatePersoon(nieuwePersoon);
} catch (ParseException ex) {
Logger.getLogger(HoofdGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
else{
Persoon nieuwePersoon = new Persoon(geselecteerdePersoon.getPersoonId(),0, txtVoornaam.getText(), txtAchternaam.getText(),null,geselecteerdePersoon.getLocatieId(),geselecteerdePersoon.getFilmId());
PersoonDao.updatePersoon(nieuwePersoon);
}
updatePersoonsLijst();
}
My method updatePersoonsLijst
public void updatePersoonsLijst() {
mijnModel.clear();
ArrayList<Persoon> lijstVanPersonen = PersoonDao.getPersonen();
for (Persoon huidigePersoon : lijstVanPersonen) {
mijnModel.addElement(huidigePersoon);
}
}
And my updatePersoon
public static int updatePersoon(Persoon nieuwePersoon) {
int aantalAangepasteRijen = 0;
try {
aantalAangepasteRijen = Database.voerSqlUitEnHaalAantalAangepasteRijenOp("UPDATE Persoon SET leeftijd=?,voornaam=?,achternaam=?,datum=?,locatieId=?,filmId=? WHERE persoonId=?", new Object[] { nieuwePersoon.getLeeftijd(),nieuwePersoon.getVoornaam(), nieuwePersoon.getAchternaam(), nieuwePersoon.getDatum(), nieuwePersoon.getLocatieId(),nieuwePersoon.getFilmId() });
} catch (SQLException ex) {
ex.printStackTrace();
// Foutafhandeling naar keuze
}
return aantalAangepasteRijen;
}
Your update statement is missing last parameter personid - your last is filmid currently.
aantalAangepasteRijen = Database.voerSqlUitEnHaalAantalAangepasteRijenOp("UPDATE Persoon
SET leeftijd=?,voornaam=?,achternaam=?,datum=?,locatieId=?,filmId=?
WHERE persoonId=?", new Object[]
{ nieuwePersoon.getLeeftijd(),
nieuwePersoon.getVoornaam(),
nieuwePersoon.getAchternaam(),
nieuwePersoon.getDatum(),
nieuwePersoon.getLocatieId(),
nieuwePersoon.getFilmId()
// persoonId missing!!
});

how to call recursively a method in a try-catch block

hi i have this problem i got a method that let a user insert a value representing the "quantity" of a product, now if the quantity wanted by the user is higher then the stock quanity it has to throw an exception and let the user input again the number i tryed it inserting a recursive call of the same method but even if it success it goes in an infinite loop like the exception is still "alive"
...
try {
if (!lol2)
throw new NegativeNumberException();
} catch (NegativeNumberException pto) {
JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
this.addToCart(cart,quant);
}
EDIT i am including now all the code but it's a bit hard so sry for the "complexity" of the code
FULL CODE
public void addToCart(ArrayList<Utilizzabile> cart,ArrayList<Integer> quant) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
boolean lol=false;
Utilizzabile us=null;
String id = JOptionPane.showInputDialog(frame, "Inserisci un ID prodotto:");
if (id ==null) { return;}
while (!id.matches("[0-9]+")) { //user inserts a value and the while checks for an int value inserted
JOptionPane.showMessageDialog(frame, "Valore inserito errato");
id = JOptionPane.showInputDialog(frame, "Inserisci un ID prodotto:");
if (id == null) { return;} }
int iden = Integer.parseInt(id);
for (Utilizzabile u: arr) { // this for loop checks if the ID inserted represents a product in the catalog
if ((u.getId() == iden) && (u.eAcquistabile())) {
lol =true;
us = u; } }
if (lol == true) { //now if the ID corresponds to an existent product it ask the user to input the quantity requested
boolean lol2=false;
String qua = JOptionPane.showInputDialog(frame, "Inserisci un quantità da aggiungere al carrello:");
if (qua ==null) { return;}
while (lol2==false) {
while (!qua.matches("[0-9]+")) {
JOptionPane.showMessageDialog(frame, "Valore inserito errato");
qua = JOptionPane.showInputDialog(frame, "Inserisci un quantità da aggiungere al carrello:");
if (qua == null) { return;} }
if (qua.length()>0 && qua.length()<=8) {
int quantit = Integer.parseInt(qua);
for (int l=0;l<cart.size();l++) { //this for checks if in the cart were already that product and then changes the quantities only
if ((cart.get(l).getId() == us.getId()) && (us.getRem()-quantit >0) ) {
int num = quant.get(l)+quantit;
quant.set(l,num);
JOptionPane.showMessageDialog(frame, "Quantità del prodotto richiesto aggiornata");
return;}
}
if ( (us.getRem()-quantit) >0) { //checks if all went good and the quantity is avaiable
JOptionPane.showMessageDialog(frame, "Prodotto della quantità richiesta aggiunto al carrello");
lol2=true;
cart.add(us);
quant.add(quantit);} }
try {
if (lol2==false)
throw new NegativeNumberException(); }
catch (NegativeNumberException pto){
JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
this.addToCart(cart,quant); }
} }
else {
JOptionPane.showMessageDialog(frame, "Prodotto non trovato");
this.addToCart(cart,quant); }
}
this code essentially is a graphical section for let the user add a product to the cart and check is everything is good but i need to place an exception to check if the quantity in stock is less then the quantity wanted by the user (i ve done it without exception with no problems but this is for an exam and i just noticed that the professor wants that i have to solve this problem by using an exception
It's not good to use recursion for that, because after "n" invocations you can receive StackOverFlowError. And I agree with #laune.
Thus I recommend to use loop. For example:
while (true){
// lol2 here is TRUE if was entered correct value and false if not.
if (lol2)
break;
else {
JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
this.addToCart(cart,quant);
}
}
insert try catch into do while loop.
when user insert correct value stop loop
E.g
int a=10;
do{
try{
if(a<20)
throw new NegativeNumberException();
else
break;
}catch (NegativeNumberException pto){
JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
//enter quantity again
// a=20;
}
}while(true);
Never use exceptions to control the regular or almost regular flow of control. It's bad programming style.
Use some do statement to repeat the dialog until a satisfactory input is achieved.
Due to lack of context, no code is provided. (Where is that recursive call??)
Later
There is room for exception handling, though. You could throw away pattern matching and length check and catch NumberFormatException.
Integer quantity = null;
do {
String id ... dialogue
try {
quantity = Integer.parseInt( id );
if( quantity <= 0 ) throw new NumberFormatException( "only positive integers" );
} catch( NumberFormatException nfe ){
... error dialogue;
quantity = null;
}
} until( quantity != null );

Empty JDateChooser

I'm using JDateChooser for a Javaapp (this is the 1st time i use it). I want to catch fault when the JDateChooser is empty with code like this:
if(dcs1.getDate().toString().isEmpty()){
lblOk.setText("Empty");
}else{
Date d = dcs1.getDate();
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
String t = df.format(d);
lblOk.setText(t);
}
JLabel lblOk;
JDateChooser dcs1;
But it dont work.
Any1 can help me plzz.
Date date;
date = JDateChooser.getDate();
if (date == null)
{
JOptionPane.showMessageDialog(null, "Choose Date from Right Box.", "Error", JOptionPane.ERROR_MESSAGE);
JDateChooser.grabFocus();
return false;
}
String s = ((JTextField)dateChooser.getDateEditor().getUiComponent()).getText();
if (s.equals("") {
JOptionPane.showMessageDialog(null, "Please type birthday", "Warning!", JOptionPane.ERROR_MESSAGE);
}
if (jDateChooserBirthDate.getDate() == null) {
JOptionPane.showMessageDialog(null, "Please type birthday", "Warning!", JOptionPane.ERROR_MESSAGE);
}
if(jDateChooser1.getDate() == null){
JOptionPane.showMessageDialog(this, "Date not selected","No selection",JOptionPane.INFORMATION_MESSAGE);
jDateChooser1.requestFocusInWindow();
}
I used DateChooserCombo. and The following code worked for me.
String test = dateChooserID.getText();
if(!test.equals("")){
//DO WHATEVER YOU WANT (DATE IS SELECTED IN THIS CASE);
}
else{
JOptionPane.showMessageDialog(this, "date not choosen");
}

Categories

Resources