Inside my Add button click i have typed some codes which works very well and inside my try catch block i have two JOptionPane messages. 1st message is to say that info has been added sucessfully and the other which is inside the catch block is to say that Client cannot be added twice to the same tour on same date.
When I run this code without any primary key violations it shows the 1st message (which is correct) but also shows the 2nd message as well. It should show only 1st message and stop. But after showing both messages it adds to the database.
When I enter something that will give primary key violation, it shows add successfully message( which is wrong) and then the Error message. It doesnt add to the database.
What am I doing wrong?
Here is my code.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DBConnection db = new DBConnection();
if (txt_name.getText().isEmpty() || txt_escort.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Cannot have empty fields");
} else {
clientID = combo_client.getSelectedItem().toString();
tourID = combo_tour.getSelectedItem().toString();
date = combo_date.getSelectedItem().toString();
escortID = txt_escort.getText();
clientName = txt_name.getText();
try {
query = "INSERT INTO tourRParticipant(ClientID,Name,TourID,StartDate,EscortID) VALUES (?,?,?,?,?)";
PreparedStatement stm = db.getconn().prepareStatement(query);
JOptionPane.showMessageDialog(null, "Added successfully!");
stm.setString(1, clientID);
stm.setString(2, clientName);
stm.setString(3, tourID);
stm.setString(4, date);
stm.setString(5, escortID);
rs = stm.executeQuery();
rs.next();
conn.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR..Client cannot be added to the same tour with the same date");
}
ViewTable();
}
}
First of all, you display the success message JOptionPane.showMessageDialog(null, "Added successfully!"); before executing the update. It should be displayed after the insert statement is executed.
Second of all, you should call executeUpdate not executeQuery, since you are executing an INSERT statement.
stm.executeUpdate();
JOptionPane.showMessageDialog(null, "Added successfully!");
JOptionPane.showMessageDialog(null, "Added successfully!");
should be after
rs = stm.executeQuery();
And as pointed in other answer, stmt.executeUpdate() should be used instead of stmt.executeQuery(). As you are passing an update query to executeQuery() method, it is throwing exception. That's why you are always getting two messages.
Related
I have MySQL database having columns named with roomno, availability, clean_status, price and room_type. Column Availability has data as either 'available' or 'not available' and column clean_status has data as either 'dirty' or 'cleaned'. I am trying to fetch data from database and if the selected room is either 'not available' or 'dirty', I would like to show error message stating 'room should be available or cleaned before adding customer'. I have used ResultSet and execute the work. Earlier it showed the error message. I modified the code and made it executable, but it doesn't give any error message neither the data in column of database has changed. I think it is because of ResultSet. Can any body help me?
try {
connection = new MySQLConnection();
} catch (Exception ae) {
if (ae != null) {
JOptionPane.showMessageDialog(null, "Error Connection To Database");
}
}
String avai ="select availability from rooms where roomno='"+roomno+"'";
String clean ="select clean_status from rooms where roomno='"+roomno+"'";
try {
this.see = connection.s.executeQuery(clean);
}
catch (SQLException ex) {
ex.printStackTrace();
}
try {
this.conn = new MySQLConnection();
this.se = connection.s.executeQuery(avai);
} catch (SQLException ex) {
ex.printStackTrace();
}
if (se.equals("Available") && see.equals("Cleaned")){
String str = "insert into customer values('" +id + "','" +mobileno +"','" +name +"','" +gender+"','"+country+"','" +roomno+"','"+checkedin+"','" +deposit+"')";
try {
connection.s.executeUpdate(str);
JOptionPane.showMessageDialog(null, "Data Added To Database");
}
catch (Exception eu) {
eu.printStackTrace();
JOptionPane.showMessageDialog(this, "Error In Database Table", "Message", JOptionPane.ERROR_MESSAGE);
}
}
else if (se.equals("Not Available") || see.equals("Dirty")){
JOptionPane.showMessageDialog(null,"Room Is Dirty or Not Available");
}
From your code se acd see are the respective ResultSet obtained, I am not sure how ResultSet.equals works, but I suggest you use the following
while(see.next())
{
String clean=see.getString("clean_status");
}
while(se.next())
{
String avail=see.getString("availability");
}
And then check the output.
However,if the error still persists, check in the table if the values for availability and clean_status are having any leading or trailing spaces, which could be an issue at times.
I have a java Swing Application that in which i'm designing a small brain challenge game. The issue is that I'm stack at the first stage of the game where I want to load the details of the current user from an sqlite database, but from two different tables. Here's my full code:
//This is the method that loads the data
private void showDetails(){
try(Connection dbConn = dbConnect.initConn()){
Statement stmt = dbConn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM status");
//Display the name of the Current User
if(rs.next()){
currentUserLbl.setText(rs.getString("currentUser"));
else{
JOptionPane.showMessageDialog(null, "An Unknown Error Occureds.");
dispose();
indexMenu im = new indexMenu();
im.setVisible(true);
}
stmt.close();
//Update the form with the other values from the database
PreparedStatement uStmt = dbConn.prepareStatement("SELECT Score, Level FROM users WHERE Name = ?");
uStmt.setString(1, currentUserLbl.getText());
ResultSet uRs = uStmt.executeQuery();
if(rs.next()){
levelLbl.setText(rs.getString("Level"));
highscoreValue.setText(rs.getString("Score"));
}
else{
//This error shows up anytime I run the code
JOptionPane.showMessageDialog(null, "An Unknown Error Occured.");
//This line also seems not to work
this.dispose();
indexMenu im = new indexMenu();
im.setVisible(true);
}
uStmt.close();
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Anytime I run the program, it shows the error I've indicated in the code. I just don't know what I've done wrong. Any help will be much appreciated.
I make this code for change password with verification. The problem is, when I clicked jbutton to change password, it works and successfully changed the password on database and show the jOptionpane Information message as well.
But after this steps, error message functioned jOptionpane is continuously showing. I try to find where the code was wrong. but couldn't yet.
private void jBtn_UpdateActionPerformed(java.awt.event.ActionEvent evt) {
String user_id = txt_UserID.getText();
String cur_pass = txt_CurrentPassword.getText();
String new_pass = txt_NewPassword.getText();
try {
Connection c = DBConnection.dbconmethod();
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT * from tch_data");
while(rs.next()) {
String userid = rs.getString("user_id");
String pass = rs.getString("password");
if(user_id.equals(userid) && cur_pass.equals(pass)) {
Statement s1 = c.createStatement();
s1.executeUpdate("UPDATE tch_data SET password='"+new_pass+"' WHERE user_id='"+user_id+"'");
JOptionPane.showMessageDialog(new view.AdminPrivacy(), "Password Succesfully Changed!", null, JOptionPane.INFORMATION_MESSAGE);
}else {
JOptionPane.showMessageDialog(new view.AdminPrivacy(), "Error : Invalid Data.", "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
You're retrieving all the rows in the database, for all the users, with your SQL query
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT * from tch_data");
Of course your username and password do not match all the rows (since you'll be seeing all the users in your database in your loop) so you always get an error message for each row except for the one that has your user in it.
You should change the query to only return the row for the user that you're changing the password for. However that requires you to use a PreparedStatement. (If you simply used the user_id in the query for a regular Statement without escaping, you'd make yourself subject to SQL injection attacks. Note that also applies to the place where you update the password - you should also use a PreparedStatement for that, otherwise you'll be in for a nasty surprise when somebody changes his password to '; DROP TABLE tch_data; SELECT * FROM tch_data 'foobar or something along those lines)
So you should replace the above two lines with these 3 lines:
PreparedStatement st = c.prepareStatement("SELECT * from tch_data WHERE user_id = ?");
st.setString(1, user_id);
ResultSet rs = st.executeQuery();
Note that you've also forgotten to close your ResultSet, Statement and Connection. You should close all of them (but most importantly the Connection), otherwise you're leaking them and your application will quickly run out of resources.
Once the Password change has been successfully made, you should break out of the while loop using the break statement. The else statement within the while loop should also be removed and placed outside of the loop. A boolean flag should be set so as to determine whether or not a successful password change has taken place and that condition checked outside the loop, for example:
try {
Connection c = DBConnection.dbconmethod();
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT * from tch_data");
boolean success = false; // **** Added Code ****
while(rs.next() && success == false) {
String userid = rs.getString("user_id");
String pass = rs.getString("password");
if(user_id.equals(userid) && cur_pass.equals(pass)) {
Statement s1 = c.createStatement();
s1.executeUpdate("UPDATE tch_data SET password='"+new_pass+"' WHERE user_id='"+user_id+"'");
success = true; // **** Added Code ****
JOptionPane.showMessageDialog(new view.AdminPrivacy(), "Password Succesfully Changed!", null, JOptionPane.INFORMATION_MESSAGE);
break; // **** Added Code ****
}
}
// **** Added Code ****
if (!success) {
JOptionPane.showMessageDialog(new view.AdminPrivacy(), "Error : Invalid Data.", "Error Message", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) { e.printStackTrace(); }
I fully agree with Erwin Bolwidt's answer, and it is IMHO the correct answer.
Since you also asked why you end up with messagedialogues --> because you're loading all users!!!
and your if-else block is wrong. if you're only changing/checking the password for one single user!
// make sure that it's the correct user
if(user_id.equals(userid)) {
// check if password was changed successfully
if(cur_pass.equals(pass)) {
// successful password change
} else {
// something went wrong with the password change
}
} else {
// this else is just to help you see your mistake
// in your code you raised the error here!
}
I am making a GUI and I need to update one column called "OCCURRENCES" whenever a patient needs help. I am using Netbeans (Java). For some reason I am not getting any errors. But My table does not Update. The executeUpdate is returning '0'. I have close all my result set statements and prepared statements at the end of the 'try', 'catch'.Also any other updates like updating from textfields, insertion of new patient and deleting patient from a table is working fine; just having problem with updating this column which initial value I have set to be zero whenever an occurrence happens I would like to call this method to increment value on column. I'm just learning to use sqlite, and I am really confuse please help here is the part of the code I am having problems with, Also it reaches the JOPtionPane message successfully.
try
{
conn = javaConnect.ConnectDB();//Returns Connection
PreparedStatement pst = conn.prepareStatement("UPDATE PEMs SET OCCURRENCES = ? "//1
+ "WHERE ROOM = ?");//2
pst.setInt(1, 1);
pst.setInt(2,1);
pst.executeUpdate();
int updated=pst.executeUpdate(); // get count to see if anything was updated
System.out.println("OCC" + updated);
JOptionPane.showMessageDialog(null, "SUCCESSFULL OCCURRENCE");
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "Error UpdateOccurence :" + e);
e.printStackTrace();`enter code here`
}finally {
try{
rs.close(); pst.close(); }
catch(Exception e) { } }
I've got the following code to query a database! But the code inside the while loop doesn't get executed! No messagebox, just doesn't get executed! Can anyone help me! Result set is not empty! When I print the same value out of the try catch block it gets executed and the right values get printed! Th DB connection is a standard MySQL DB connection class!
database = new DBConnection();
String dept = txtSearch.getText();
String Query = "SELECT * FROM department where dept_name= '" + dept + "'";
ResultSet set = database.queryDatabase(Query);
try {
if (set.next() == false) {
JOptionPane.showMessageDialog(null, "No Matchs found for the search query! Try Again.", "Search Error", JOptionPane.ERROR_MESSAGE);
} else {
while (set.next()) {
System.out.print(set.getString("dept_name"));
txtName.setText(set.getString("dept_name"));
txtDes.setText(set.getString("dept_desc"));
}
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), ex.getCause().toString(), JOptionPane.ERROR_MESSAGE);
}
You're throwing out the first row of your query by calling set.next() and then ignoring the data in the row here:
if (set.next() == false) { // ***** here on this line
JOptionPane.showMessageDialog(null, "No Matchs found for the search query!
Try Again.", "Search Error", JOptionPane.ERROR_MESSAGE);
} else {
while (set.next()) {
System.out.print(set.getString("dept_name"));
txtName.setText(set.getString("dept_name"));
txtDes.setText(set.getString("dept_desc"));
}
}
Instead be sure to extract information from your ResultSet every time you call next() and it returns true.
You could do something like this instead:
int setCount = 0;
while (set.next()) {
setCount++;
System.out.print(set.getString("dept_name"));
txtName.setText(set.getString("dept_name"));
txtDes.setText(set.getString("dept_desc"));
}
if (setCount == 0) {
// show a warning to the user that the result set was empty
}