I have this error when using PreparedStatements
to insert a User into a table in Postgresql
called " user
", this action is carried out by crushing a button with the help of a PostgresHelper:
PostgresHelper client = new PostgresHelper(DbContract.HOST, DbContract.DB_NAME, DbContract.USERNAME,DbContract.PASSWORD);
btnRegisterUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent var1) {
// Register the new user in the db
try {
client.insertUser(new User(getAllData()));
} catch (SQLException e) {
System.out.println("Could't register the user");
e.printStackTrace();
}
// Cleans textboxs
cleanTextBoxs();
}
});
The class PostgresHelper
that contains the method to save the user in its respective user table:
package Controller;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import Model.User;
import java.sql.*;
public class PostgresHelper {
private Connection conn;
private String host;
private String dbName;
private String user;
private String pass;
private static final String INSERT_USER = "INSERT INTO user "
+ "(userid, name, surname, password, codice_fiscale) VALUES (?,?,?,?,?)";
public PostgresHelper(String host, String dbName, String user, String pass) {
this.host = host;
this.dbName = dbName;
this.user = user;
this.pass = pass;
}
public boolean connect() throws SQLException, ClassNotFoundException {
if (host.isEmpty() || dbName.isEmpty() || user.isEmpty() || pass.isEmpty()) {
throw new SQLException("Database credentials missing");
}
Class.forName("org.postgresql.Driver");
this.conn = DriverManager.getConnection(this.host + this.dbName, this.user, this.pass);
return true;
}
public void insertUser(User user) throws SQLException {
String userId = user.getUserID();
String name = user.getName();
String surname = user.getSurname();
String password = user.getPassword();
String codiceFiscale = user.getCodiceFiscale();
PreparedStatement pstmt = conn.prepareStatement(INSERT_USER);
pstmt.setString(1, userId);
pstmt.setString(2, name);
pstmt.setString(3, surname);
pstmt.setString(4, password);
pstmt.setString(5, codiceFiscale);
pstmt.executeQuery();
System.out.println("User registered");
}
}