I'm trying to fetch database records of user name and password and validate using if-else statement. Final else statement is not displaying message dialog. I'm stuck with this, suggest me a solution and say where i done mistake.
My complete code
String s1 = id.getText();
String s2 = new String(pass.getPassword());
try
{
Class.forName("org.apache.hive.jdbc.HiveDriver");
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/twitter_db","arunachalam","");
String sql = "select userid, password from user_reg where userid='"+s1+"'";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
if((rs.getString("userid").equals(s1)) && (rs.getString("password").equals(s2)))
{
dispose();
showMessageDialog(null,"Login Successfully");
new UserPage().setVisible(true);
}
else if((rs.getString("userid").equals(s1)) && (!rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect Password");
}
else
{
showMessageDialog(null,"Invalid User");
}
}
}
catch(Exception e)
{
showMessageDialog(null, e);
}
You checked same condition twice for user id and password so every time it checks first else if statement and it does't satisfy final else if.
Obeserve in your below piece of source code.
else if((rs.getString("userid").equals(s1)) && (!rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect Password");
}
else if((rs.getString("userid").equals(s1)) && (!rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect Password");
}
May be you are trying for below code that i have updated
// check for user id not equal
else if((!rs.getString("userid").equals(s1)) && (rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect User Id");
}
else if((rs.getString("userid").equals(s1)) && (!rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect Password");
}
Related
I am doing a project in Java Swing and using SQLite as my database.
This is the function I wrote for deleting a record from the Room table in my database.
public void Delete() {
String room_code = jTextField5.getText();
String sql = "DELETE FROM Room WHERE room_code = '" + room_code + "'";
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null, "Room Deleted Successfully");
}
else {
JOptionPane.showMessageDialog(null, "Invalid Room Code");
}
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
However, I am met with the following Exception: SQLException: query does not return results.
I have tried to use pst.executeUpdate() as suggested in other answers but it says "int cannot be converted into resultset".
A DELETE statement does not return a result set. You should call method executeUpdate rather than method executeQuery.
Also, you can use place holders with a PreparedStatement.
Also you should use try-with-resources
Consider the following code.
public void Delete() {
String room_code = jTextField5.getText();
String sql = "DELETE FROM Room WHERE room_code = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(room_code);
int count = ps.executeUpdate();
if (count > 0) {
JOptionPane.showMessageDialog(null, "Room Deleted Successfully");
}
else {
JOptionPane.showMessageDialog(null, "Invalid Room Code");
}
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
For some reason, I have an else if statement that does not want to run. The conditions (I think) have been met.
int codeCheck = Integer.parseInt(itemCode);
DataAccessImpl da = new DataAccessImpl();
if(!rs.wasNull()) {
while(rs.next()) {
Products temp = new Products(rs.getString(1), rs.getString(2), rs.getDouble(3), rs.getBoolean(4));
productsList.add(temp);
request.setAttribute("productsList", productsList);
request.getRequestDispatcher("Scan.jsp").forward(request, response);
}
}
else if(da.codeExists(codeCheck) == false){
Products wrongCode = null;
productsList.add(wrongCode);
System.out.println("THIS IS EXECUTING!");
request.setAttribute("productsList", productsList);
request.getRequestDispatcher("Scan.jsp").forward(request, response);
}
Here's the method in the DataAccessImpl Class
public boolean codeExists(int code) {
final String SELECT_QUERY = "SELECT * FROM productcatalogue WHERE code = ?";
try {
PreparedStatement statement = conn.prepareStatement(SELECT_QUERY); // Create query statement
statement.setInt(1, code);
ResultSet queryResult = statement.executeQuery();
if (!queryResult.next()) { // Check if code entered exists
return false;
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return true; //Otherwise the item exists
}
if you are sure rs was surely null and the first if is not met then definitely it will go to your else if and will check if (da.codeExists(codeCheck) == false) and if this is also true then it will surely execute so you make sure that first if is false and else if is true other wise according to the design pattern it will not be executed.
My complete code to access data from two different databases using single hive jdbc driver. I get sql exception on next database connection, before that it works perfectly. Kindly, suggest me some solution to further process. Where as next prepared statement query throws sql exception. But doing on a separate button action it works fine, while i'm doing in a single action it throws error.
String s1 = jTextField1.getText();
String s2 = jTextField2.getText();
String s3 = jTextField3.getText();
String s4 = new String(jPasswordField1.getPassword());
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/twitter_db", "arunachalam", "");
Statement st = con.createStatement();
String sql = "select dbname,tbname from check where userid='" + s3 + "'and tbname='" + s2 + "'";
String sql1 = "select userid,password from user_reg where userid='" + s3 + "'";
ResultSet rs = st.executeQuery(sql);
try {
PreparedStatement ps = con.prepareStatement(sql1);
ResultSet rs1 = ps.executeQuery();
while (rs.next() && rs1.next()) {
if ((rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
jSeparator1.setVisible(true);
jScrollPane1.setVisible(true);
try {
Connection con1 = DriverManager.getConnection("jdbc:hive2://localhost:10000/" + s1, "arunachalam", "");
ArrayList<Tweet> list = new ArrayList<Tweet>();
String ve = "select id,created_at,source,favorited,retweet_count,retweeted_status,entities,text,user,in_reply_to_screen_name from " + s2;
PreparedStatement ps1 = con1.prepareStatement(ve);
ResultSet rs2 = ps1.executeQuery();
Tweet tweet;
while (rs2.next()) {
tweet = new Tweet(rs.getLong("id"), rs.getString("created_at"), rs.getString("source"), rs.getBoolean("favorited"), rs.getInt("retweet_count"), rs.getString("retweeted_status"), rs.getString("entities"), rs.getString("text"), rs.getString("user"), rs.getString("in_reply_to_screen_name"));
list.add(tweet);
String[] columnName = {"Tweet_ID", "Created_At", "Source", "Favorited", "Retweet_Count", "Retweeted_Status", "Entities", "Text", "User", "Screen_Name"};
Object[][] twt = new Object[list.size()][10];
for (int i = 0; i < list.size(); i++) {
twt[i][0] = list.get(i).gettweetid();
twt[i][1] = list.get(i).getcreated();
twt[i][2] = list.get(i).getsource();
twt[i][3] = list.get(i).getfavor();
twt[i][4] = list.get(i).getcount();
twt[i][5] = list.get(i).getstatus();
twt[i][6] = list.get(i).getentities();
twt[i][7] = list.get(i).gettext();
twt[i][8] = list.get(i).getuser();
twt[i][9] = list.get(i).getscreen();
TheModel model = new TheModel(twt, columnName);
jTable1.setModel(model);
jTable1.setRowHeight(20);
}
}
} catch (Exception e) {
showMessageDialog(null, e);
}
break;
} else if ((!rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Database Name is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((rs.getString("dbname").equals(s1)) && (!rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Table Name is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (!rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Password is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((!rs1.getString("userid").equals(s3)) && (rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "User ID is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else {
JOptionPane.showMessageDialog(null, "Access Denied", "Error", JOptionPane.ERROR_MESSAGE);
}
}
} catch (Exception e) {
showMessageDialog(null, e);
}
} catch (Exception e) {
showMessageDialog(null, e);
}
To be responsive, as the application would freeze during actionPerformed use
invokeLater.
Yes separate connections for instance with different users, one for reading only, one for admin tasks, is quite possible. However I did not see calls to close().
(Also a single-user (such as an embedded) database might not do.)
To automatically close connection, statement and result set use try-with-resources: try (DECLARATION; ... ; DECLARATION) { ... } - saves a lot.
The explicit class loading with Class.forName no longer is needed for current drivers.
// Java 8
SwingUtilities.invokeLater(() -> {
String sql = "select dbname, tbname from check where userid=? and tbname=?";
try (Connection con = DriverManager.getConnection(
"jdbc:hive2://192.168.1.13:10000/twitter_db", "arunachalam", "");
PreparedStatement st = con.prepareStatement(sql)) {
st.setString(1, s3);
st.setString(2, s2);
try (ResultSet rs = st.executeQuery()) {
if (rs.next()) {
List<Tweet> list = new ArrayList<>();
String hive = "select id,created_at,source,favorited,retweet_count,"
+ "retweeted_status,entities,text,user,in_reply_to_screen_name from "
+ s2;
try (Connection con1 = DriverManager.getConnection(
"jdbc:hive2://localhost:10000/"+s1, "arunachalam", "");
PreparedStatement ps1 = con1.prepareStatement(hive);
ResultSet rs2 = ps1.executeQuery()) {
...
});
The password and username are retrieved from the database. If one row is returned, a user exists. However, the below code says that the user does not exist even if the username and password are correct.
if(con != null) {
try {
String query = "select * from users where username = '"+user.getText()+"' and password = '"+pasword.getText()+"'";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
int count = 0;
while(rs.next()) {
count = count + 1;
}
if(count == 1) {
JOptionPane.showMessageDialog(null, "user exist");
} else {
JOptionPane.showMessageDialog(null, "user doesnot exist");
}
rs.close();
ps.close();
} catch (Exception e1) {
}
}
It´s a sensible code, but you should to write the
e.printStackTrace()
in the catch block, maybe an exception it's occurs. Check the user.getText() and password.getText() content, also you can apply an user.getText().trim() for example, to delete de blank spaces. Then try this:
while(rs.next()) {
count++;
}
if(count > 0) {
JOptionPane.showMessageDialog(null, "user exist");
} else {
JOptionPane.showMessageDialog(null, "user doesnot exist");
}
Good luck!
I am trying to show a messagebox when either the username or password textbox is empty but when I run the project the only textbox showing is "JOptionPane.showMessageDialog(null,"Your Username or Password is incorrect");" Please help and Thank You!
private void jButton1ActionPerformed(ActionEvent evt) {
String user=txtUsername.getText();
char[] pass=txtPassword.getPassword();
if(user == null) {
JOptionPane.showMessageDialog(null,"Username Field is empty");
} else if(pass==null) {
JOptionPane.showMessageDialog(null,"Password Field is empty");
} else {
String sql="select * from account where username=? and password=?";
try{
pst=conn.prepareStatement(sql);
pst.setString(1,txtUsername.getText());
pst.setString(2,txtPassword.getText());
rs=pst.executeQuery();
if (rs.next()) {
GridlockMain a=new GridlockMain();
a.setVisible(true);
} else {
JOptionPane.showMessageDialog(null,"Your Username or Password is incorrect");
txtUsername.setText(null);
txtPassword.setText(null);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null,e);
}
}
}
JTextField.getText() does not return null if you keep it empty. Try to check value using isEmpty method at if condition.
String user=txtUsername.getText();// It return empty String ""
// even no data is entered.
if(user.isEmpty){
JOptionPane.showMessageDialog(null,"Username Field is empty");
}
......
try this..
if(!user.length() > 0){
JOptionPane.showMessageDialog(null,"Username Field is empty");
}
else if(!pass.length > 0){
JOptionPane.showMessageDialog(null,"Password Field is empty");
}
I also struggled with the text Validation process. I found a very easy way to test this. Here, instead of using JOptionPane to show a message to the user, I just didn't allow them to enter, or press the button. Here's my code:
//Validate whether user Has input some information:
if(UserNameTA.getText() == null || UserNameTA.getText().trim().isEmpty())
{
btnEnter.setEnabled(false);
}
else
{
//Make a new JFrame for login
new ProfileHome().setVisible(true);
frame.dispose();
}
btnEnter.setEnabled(true);
I hope this at least guides you to your success.
It returns an empty string "" compare the
StringUtils.isEmpty(txtUsername.getText())
String user = txtUsername.getText();
String pw = txtPassword.getText();
if(user.isEmpty() || (pw.isEmpty()))
{
JOptionPane.showMessageDialog(null, "Your Username or Password is incorrect" );
}
else
{
//proceed to query
if (user.length() == 0) {
JOptionPane.showMessageDialog(null, "Username Field is empty");
} else if (pass.length() == 0) {
JOptionPane.showMessageDialog(null, "Password Field is empty");
}