Column index out of range: 2, column number 1

I have this column:

Klas_student

CREATE TABLE IF NOT EXISTS Klas_student(
Student varchar(7) REFERENCES studenten (Studentenummer) ON DELETE CASCADE NOT NULL,
Klas text NOT NULL REFERENCES Klas (Naam_id) ON DELETE CASCADE NOT NULL
);

      

In this column I want to add values, I do it using prepared state.

PreparedStatement studentToKlas = conn.prepareStatement("INSERT INTO Klas_student " + "VALUES (?)");
                studentToKlas.setString(1, studentnummer);
                studentToKlas.setString(2, klasIdToInsert);

      

However, this error keeps popping up:

org.postgresql.util.PSQLException: L'indice de la colonne est hors limite : 2, nombre de colonnes : 1.
at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:56)
at org.postgresql.core.v3.SimpleParameterList.setStringParameter(SimpleParameterList.java:118)
at org.postgresql.jdbc2.AbstractJdbc2Statement.bindString(AbstractJdbc2Statement.java:2304)
at org.postgresql.jdbc2.AbstractJdbc2Statement.setString(AbstractJdbc2Statement.java:1392)
at org.postgresql.jdbc2.AbstractJdbc2Statement.setString(AbstractJdbc2Statement.java:1374)
at PerformanceClass$1.run(PerformanceClass.java:73)
at java.lang.Thread.run(Thread.java:724)

      

It basically says that the column index is above the limit: 2, and the number of columns is one.

PerformanceClass.java:73 is the line of code:

 studentToKlas.setString(2, klasIdToInsert);

      

As you can see, Klas_student has two fields, so I don't really understand the error. Do any of you see what I'm doing is breaking?

+3


source to share


3 answers


You have two columns, so your statement should be:

"INSERT INTO Klas_student VALUES (?, ?)")

      



i.e. it must contain two placeholders, one for each column.

+2


source


This is because you only bind one parameter here:

("INSERT INTO Klas_student " + "VALUES (?)")

      



Change it to:

 ("INSERT INTO Klas_student " + "VALUES (?,?)")

      

+1


source


This is your statement:

INSERT INTO Klas_student " + "VALUES (?)

      

The table Klas_student

has two columns. So this is equivalent to:

INSERT INTO Klas_student(Student, Klas) " + "VALUES (?)

      

Now you can clearly see what the error is. There are two columns that you insert. In your case, both columns are not NULL, so you need to enter two values:

INSERT INTO Klas_student(Student, Klas) " + "VALUES (?, ?)

      

The reason I am adding an answer is to emphasize that you should always include the column list when you execute INSERT

. Do not accept numbers or order of values. This might make sense to you when you are writing code. It won't be obvious what you are doing two weeks later. It won't make sense for anyone else to read the code. Be clear.

+1


source







All Articles