Search code examples
javadatabasesqliteprepared-statementsqlexception

SQL Exception error when trying to execute the query to sqllite database


I am trying to query database from login application to the SQLite database. Once the user enter user name and password and clicked enter it should check the credentials in the database. When I clicked login button it is showing:

java.sql.SQLException:sql error or missing database

Below is the code for better understanding. What is the error in the code?

Note:

  • I have Login table in my database.
  • The connection is successful

try
{
    String query="select * from Login where username=? Password=?";
    PreparedStatement pst=connection.prepareStatement(query);
    pst.setString(1, userField.getText());
    pst.setString(2, passwordField.getText());
    ResultSet rs=pst.executeQuery();
    int count=0;
    
    while(rs.next()) {
        count=count+1;
    }
    
    if(count==1) {
        JOptionPane.showMessageDialog(null, "Username and Password is correct");
    }
    else if (count>1)
    {
        JOptionPane.showMessageDialog(null, " Duplicate Username and Password is correct");
    }
    else
    {
        JOptionPane.showMessageDialog(null, "  Username and Password is not correct");
    }
    rs.close();
    pst.close();

} catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
}

Solution

  • String query="select * from Login where username=user123 Password=password123";
    PreparedStatement pst=connection.prepareStatement(query);
    pst.setString(1, userField.getText());
    //pst.setString(2, passwordField);
    

    The basics of using a PreparedStatement should be something like:

    String query="select * from Login where username = ? and Password = ?";
    PreparedStatement pst=connection.prepareStatement(query);
    pst.setString(1, userField.getText());
    pst.setString(2, passwordField.getText());
    

    That is the query string indicates where you want to add parameters to the string. Then you need to replace the parameters with values from the text components of your GUI.

    Also, why do you have a while loop? Isn't the point of the query to determine if the userid/password are found in the database? If so there can only ever be one entry returns in the ResultSet.

    Read the section on JDBC Database Access for SQL basics.

    This question has nothing to do with Swing. First learn how to do the SQL query properly by hardcoding the userid/password values in the setString(...) method. Once you get this working, then you try to do the query with dynamic data that you get from a text field in your GUI.