-1

I tried to create a login form and it is showing Column index is out of range. I have created two columns and I have used two columns but it is showing error.

String url = "jdbc:mysql://localhost:3306/login_form?useSSL=false";
String name = "Vzlys";
String Pass = "Vzlys@1995";
   try 
    {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection(url,name,Pass);
        st = con.prepareStatement("select * from login where username = ? and password = ?");//here login is my table name
        st.setString(1,txtusername.getText());
        st.setString(2,txtpassword.getText());//error occurs here
        rs = st.executeQuery();
        JOptionPane.showMessageDialog(null,"Welcome");
        ferrysql f = new ferrysql();
        f.setVisible(true);
        con.close();
        st.close();
    } 
    catch (Exception e) 
    {
       JOptionPane.showMessageDialog(null,e);
    }

2 Answers2

2

In your code:

 st = con.prepareStatement("query");

Means your query is : query

But if you use ;

 String query= "select * from table A where column1 = ?";
 st = con.prepareStatement(query);

Note: in this staement query is not within inverted commas.

Hope this will help.

MinA
  • 405
  • 4
  • 9
0
  1. st = con.prepareStatement("query"); Above line shows that your query is "query" not the variable, which you might have been used in your program

  2. It may be due to your txtpassword.getText() is null at line st.setString(2,txtpassword.getText());

    print both txtusername and txtpassword to check both filed contains data or not before using at preparedStatement

If you are checking user name and password then you have to use following query

PreparedStatement st = con.prepareStatement("select * from user where 
(userName = ? and password = ?");
         st.setString(1,txtusername.getText());
        st.setString(2,txtpassword.getText());

This should work

xrcwrn
  • 5,339
  • 17
  • 68
  • 129