Answer the question
In order to leave comments, you need to log in
Why doesn't preparedStatement work when working with Postgres?
package com.company.Labs.Lab_6;
import java.sql.*;
public class Final_test {
public void ex1() {
try {
//Задание 1
Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testDB", "postgres", "1703");
Statement statement = connection.createStatement();
statement.execute("drop table if exists students");
statement.execute("create table students (ID int primary key not null, NAME varchar(20) not null" +
", AGE int not null , STUDY_OR_NOT boolean not null, HEIGHT float not null)");
PreparedStatement preparedStatement = connection.prepareStatement("insert into students (ID,NAME,AGE,STUDY_OR_NOT,HEIGHT) values (?,?,?,?,?)");
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, "Daniil");
preparedStatement.setInt(3, 20);
preparedStatement.setBoolean(4, true);
preparedStatement.setFloat(5, 1.82f);
int n = preparedStatement.executeUpdate();
System.out.println(n); // выводит 1, то есть все крашится на том, что id, якобы повторяется и я его будто 2 раза записываю.
ResultSet resultSet = statement.executeQuery("select * from students");
while (resultSet.next()) {
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
int age = resultSet.getInt(3);
boolean study_or_not = resultSet.getBoolean(4);
float height = resultSet.getFloat(5);
preparedStatement.executeUpdate();
System.out.println(id + "/" + name + "/" + age + "/" + study_or_not + "/" + height);
}
statement.close();
preparedStatement.close();
connection.close();
} catch (SQLException e) {
System.err.println(e);
}
}
}
org.postgresql.util.PSQLException: ERROR: Duplicate key value violates unique constraint 'students_pkey'
Details: Key '(id)=(1)' already exists.
Answer the question
In order to leave comments, you need to log in
Because you already have a record in the database with primary key 1. The problem is not in PostgreSQL and not in preparedStatement.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question