Reputation: 65
I have this tabel :
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 tabel i want to add values, i do that this way with preparedstatement.
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 index of the columnis beyond limit : 2, and number of columns is one.
PerformanceClass.java:73 is this line of code :
studentToKlas.setString(2, klasIdToInsert);
As you can see Klas_student has two fields, so i don't really understand the error. Does any one of you see what i am doing wrang?
Upvotes: 3
Views: 1786
Reputation: 1269773
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, you are inserting one. In your case, both columns are not-NULL, so you need to put in two values:
INSERT INTO Klas_student(Student, Klas) " + "VALUES (?, ?)
The reason I'm adding an answer, though, is to emphasize that you should always include a column list when doing INSERT
. Do not assume the number or ordering of the values. It might make sense to you when you write the code. It won't be apparent what you are doing two weeks later. It won't make sense to anyone else reading the code. Be explicit.
Upvotes: 1
Reputation: 393831
You have two columns, so your statement should be :
"INSERT INTO Klas_student VALUES (?, ?)")
i.e. it should contain two placeholders, one for each column.
Upvotes: 2
Reputation: 4268
It is because you are binding only 1 parameter here:
("INSERT INTO Klas_student " + "VALUES (?)")
Change it to:
("INSERT INTO Klas_student " + "VALUES (?,?)")
Upvotes: 1