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.
Related
I want to select all data from database table between given 2 specific dates and add that data to a jtable.
Below is my code to retrieve data from the database; But all the data is not shown by this code .. What is the error I done here?
private void updateTable(){
String fday = ((JTextField)day_chooser.getDateEditor().getUiComponent()).getText();
String tday = ((JTextField)day_chooser.getDateEditor().getUiComponent()).getText();
try {
String sql = "SELECT * FROM saleinfo WHERE SaleDate BETWEEN '"+fday+"' AND '"+tday+"'";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
tbl.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error : "+ex);
}
}
Leverage the JDBC drive and it's ability to map between data types from Java to the database, leverage the power of the PreparedStatement
I'm using prepared statements pst is the prepare statement
BUT, you're not using it properly, see Using Prepared Statements for more details.
Start by getting the Date value from the date picker (I'm guessing here, but I assume they have some kind of getDate method) and then bind the values to the wildcard columns of the query, for example...
Date fday = day_chooser.getDate();
Date tday = day_chooser.getDate();
try {
String sql = "SELECT * FROM saleinfo WHERE SaleDate BETWEEN ? AND ?";
try (PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setDate(1, new java.sql.Date(fday.getTime()));
pst.setDate(2, new java.sql.Date(tday.getTime()));
try (ResultSet rs = pst.executeQuery()) {
tbl.setModel(DbUtils.resultSetToTableModel(rs));
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error : " + ex);
ex.printStackTrace();
}
Don't assume anything about the format, this will just cause you no end of grieve if you ever have to change databases
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.
No error is showing when i click the button but the table on the database doesn't update.
String heh = jLabel17.getText();
try {
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
}catch (SQLException err) {
System.out.println(err.getMessage() );
}
You have messed up the query totally,
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
should be,
stmt.executeUpdate("UPDATE books SET availability='Unavailable' where Book_title='"+heh+"' ");
It is advisable to print query before you execute , as that avoids common mistakes. Also try to use Prepared Statements as yours is vulnerable to sql injection
Read this Prepared Statements and JDBC Drivers
AFTER HOURS OF RESEARCH, I FOUND THE SOLUTION, I REPLACED THIS
String heh = jLabel17.getText();
try{
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
}catch(SQLException err){
System.out.println(err);
}
WITH THIS CODE
String heh = jLabel17.getText();
try{
con = DriverManager.getConnection("jdbc:derby://localhost:1527/Dafuq7","Dafuq7","Dafuq7");
// Creating Statement for query execution
stmt = con.createStatement();
// creating Query String
String query = "UPDATE books SET availability='NOT AVAILABLE' WHERE book_title='"+heh+"'";
// Updating Table
int rows = stmt.executeUpdate(query);
System.out.println(rows + " Rows Updated Successfully....");
} catch (Exception e) {
System.out.println(e.toString());
}
I am trying to verify username and password with MySQL. But it's not working. I can't find the problem. Can anybody help me fix it?
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String user = jTextField1.getText();
char[] pass = jPasswordField1.getPassword();
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
rs = stat.executeQuery(sql);
while (rs.next())
{
if (user.equals(rs.getString("username")))
{
if (pass.equals(rs.getString("password")))
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
}
stat.close();
con.close();
}
catch (SQLException | HeadlessException e)
{
//e.printStackTrace();
JOptionPane.showMessageDialog(null,"PROBLEM OCCURED !!!! ");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}
Actually I think it is not checking the enteries with username and password in database. am I right?
Firstly, select by username, then hash the user entered password en check if it matches the hashed password in the database. I suggest something like SHA-2
I also suggest you write classes to handle your code, i.e a User class..
You also forgot to close your ResultSet
One more thing, use PreparedStatement
You are checking for password and username match 2 times.
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
There you already check the password and user, First you shuld check if the password its not stored as MD5 or any other hash type
After that sql you only need to check if its returns any row like #Prabhakaran says
Check code which is written is connecting to database, password is not there in the below code
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Second is check the user and pass variable is getting the value from the action event.
Do like this
Statement stat = con.createStatement();
user = user.toLowerCase();
pass = pass.toLowerCase();
String sql = "Select * from tbl_User Where LOWER(username)='" + user + "' and LOWER(password)='"+pass+"'";
rs = stat.executeQuery(sql);
if(rs.next())
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
First things first.
Code will only be used to validate the error. So you must paste the error fired by your program.
Since we don't have enough information to the problem, I will try to help you out.
1- It seems your connection variable missing the "Connection" try this :
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"DATABASENAME"?useTimezone=true&serverTimezone=UTC","USERNAME","PASSWORD");
2 - You already made the if statement to the query in the beginning, so you don't have to start all over again with You can simply type :
if (rs.next()) {
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
} then carry on with the exception part
this is the code :
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
rs = stat.executeQuery(sql);
if (rs.next())
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
stat.close();
con.close();
}
catch (SQLException | HeadlessException e)
{
//e.printStackTrace();
JOptionPane.showMessageDialog(null,"PROBLEM OCCURED !!!! ");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}`
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
}