-1

It gives this error:

"java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0). "

This is the code:

public void insertData(int id,String name, String status, String age){



     String sql = "INSERT INTO student_table (id,name,satus,age) VALUES  (id,name,status,age)";

     try (Connection conn1 = this.connects();PreparedStatement Prepst= conn1.prepareStatement(sql)){

     Prepst.setInt(1, id);
     Prepst.setString(2, name);
     Prepst.setString(3, status);
     Prepst.setString(4, age);
     Prepst.executeUpdate();

     }catch(Exception e){
            System.err.println(e);

      }

If I change the parameter index to another value i.e.:

Prepst.setInt(0, id);

then it gives this error:

" java.sql.SQLException: Parameter index out of range (0 < 1 ). "

----UPDATE -----

I inserted this code:

String sql = "INSERT INTO student_table (id,name,satus,age) VALUES  (?,?,?,?)";

It produces the same:

RESULT

Table Structure:

HERE

5
  • Please have a look at Java naming conventions: oracle.com/technetwork/java/codeconventions-135099.html Commented Apr 5, 2018 at 11:15
  • 1
    The version with (?,?,?,?) is correct, but the first parameter is at position 1, not 0. Commented Apr 5, 2018 at 11:27
  • ok sorry my bad for that i was trying different ways. After correcting it it gives this --> com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'satus' in 'field list' Commented Apr 5, 2018 at 11:29
  • could you send me the table structure/schema ? Commented Apr 5, 2018 at 11:30
  • @KlaydPro Maybe status, not satus? Anyway, your question is answered. Please don't extend it with "help me debug my code until I get the correct result" comments. Commented Apr 5, 2018 at 11:32

2 Answers 2

3

Your SQL expression

INSERT INTO student_table (id,name,satus,age) VALUES  (id,name,status,age)

actually does not have any parameters. Try with:

INSERT INTO student_table (id,name,satus,age) VALUES  (?,?,?,?)
Sign up to request clarification or add additional context in comments.

1 Comment

@KlaydPro Please read JavaDocs of PreparedStatement. In PreparedStatement indexing of parameters starts with 1, not 0.
0

Try this...

public void insertData(int id,String name, String status, String age){



     String sql = "INSERT INTO student_table (id,name,satus,age) VALUES  (?,?,?,?)";

     try (Connection conn1 = this.connection;PreparedStatement Prepst= conn1.prepareStatement(sql)){

     Prepst.setInt(1, id);
     Prepst.setString(2, name);
     Prepst.setString(3, status);
     Prepst.setString(4, age);
     Prepst.executeUpdate();

     }catch(Exception e){
            System.err.println(e);

      }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.