This message gives me when it makes the insert in the database and does not give any error only gives this warning message.
Advertencia: The class RepeatableWriteUnitOfWork is already flushing. The query will be executed without further changes being written to the database. If the query is conditional upon changed data the changes may not be reflected in the results. Users should issue a flush() call upon completion of the dependent changes and prior to this flush() to ensure correct results.
NclDocumento documento = null;
try {
NclTipoDocumento tipo = findTipoDocumentoById(tipoD.getValue());
if (numero != null && numero != 0 && anioSelected != null) {
documento = findAcuerdoByNumeroAndAnioAndTipoDocumento(numero, anioSelected, tipo);
if (documento != null) {
return new Response<>(documento, ResponseStatus.OK_INSERT);
}
}
if (documento == null) {
documento = new NclDocumento();
documento.setNumero(122);
documento.setAnio(2014);
documento.setFechaEmision(new Date());
documento.setIdTipoDocumento(em.find(NclTipoDocumento.class,1));
if (firma != null && firma.getEmpleado() != null) {
documento.setIdFirma(firma.getEmpleado());
}
documento.setFechaCreacion(new Date());
documento.setUsuarioCreacion(usuarioLogueado);
documento.setActivo(true);
}
em.persist(documento);
em.flush();
return new Response<>(documento, ResponseStatus.OK_INSERT);
} catch (ConstraintViolationException ex) {
String validationError = getConstraintViolationExceptionAsString(ex);
log.error(validationError);
context.setRollbackOnly();
return new Response<>(ResponseStatus.ERROR_PARAMS, "Sucedio un error con la información: " + validationError);
} catch (Exception ex) {
processException(ex);
context.setRollbackOnly();
return new Response<>(ResponseStatus.ERROR, "Sucedio un error: " + ex.getMessage());
}
Related
This question already has answers here:
Struts2 passing variables case
(3 answers)
Closed 1 year ago.
i recently try to learn java and struts.
i want to pass the selected value from my dropdown but all i receive in my action is null
here's my code
dropdown in my jsp
<s:select list="UrgencyList" listKey="name" listValue="name"
key="urgency" name="urgency" emptyOption="false" headerKey="12" required="true"
headerValue="--------------------------------------------------------" />
<font class="ui-widget-R"><s:property value="errors['urgency'][0]" /></font>
my xml, SavSharing is the post action used ob my button
<action name="SavSharing" class="com.ao.qshare.form.Sharing" method="Save">
<exception-mapping exception="org.apache.commons.fileupload.FileSizeLimitExceededException"
result="error" />
<result name="success">/qs/sharing.jsp</result>
<result name="input">/qs/sharing.jsp</result>
<interceptor-ref name="basicStack"/>
<interceptor-ref name="mydefault" />
</action>
public class Sharing extends ActionSupport {
public String Save() throws Exception {
String result = "";
SharingSqlManger sql = null;
SiteDeploySqlManger sSql=null;
try {
Log.info(getClass(), "-----Save start-----");
con = DbConnection.getDbConnection();// get account
con.setAutoCommit(false);
sql=new SharingSqlManger(con);
sSql= new SiteDeploySqlManger(con);
ActionContext actionContext = ActionContext.getContext();
Map<?,?> data=actionContext.getParameters();
String tp=SharingUtil.getString(data.get("tp"));
attachs=SharingUtil.getFile(this.sno,SharingConstants.sharing);
boolean isSameFile=SharingUtil.isSameFile(SharingUtil.getFileString(attachs),this.getUploadFileName());
// boolean isSameFile=SharingUtil.isSameFile(this.attach,this.getUploadFileName());
//save
this.setPara();
String oldStatus=entity.getStatus();
if (isSameFile){
this.addActionMessage(SharingConstants.messFileExists);
mess.add(SharingConstants.messFileExists);
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}else{
//upload!=null,do upload
if (!GenericValidator.isBlankOrNull(this.getUploadFileName())) {
this.setAttach(this.attach+this.getUploadFileName()+";");
entity.setAttach(this.attach);
}
if (tp.equals("File")){
if (this.lengthValidate() && this.isSaveValidate(sql)){
if (status.equals(SharingConstants.deployStatusKey)) {
SharingEntity shEntity = sql.getSharing(sno, "</p>");
entity.setAlertSite(shEntity.getAlertSite());
entity.setAlertDept(shEntity.getAlertDept());
entity.setDeployDept(shEntity.getDeployDept());
entity.setDeploySite(shEntity.getDeploySite());
entity.setDSite(shEntity.getDSite());
entity.setDDept(shEntity.getDDept());
//Start CR-2014-01727 Kevin
entity.setAlertCopy(shEntity.getAlertCopy());
entity.setDeployCopy(shEntity.getDeployCopy());
//End CR-2014-01727 Kevin
}
//save
sno = sql.save(entity,SharingConstants.saveDocument,SharingConstants.sharing,oldStatus);
this.setSno(sno);
entity=sql.getSharing(sno,"</p>");
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
if (upload != null)
SharingUtil.getFile(upload, this.getUploadFileName(), sno,
SharingConstants.sharing);
init(sql);
con.commit();
Log.info(getClass(), "-----Save end-----");
isValidate=true;
result = SUCCESS;
}else{
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}
}else{
if (this.status.equals(SharingConstants.newStatusKey)){
this.setStatus(SharingConstants.drafStatusKey);
if (this.lengthValidate() && this.isSaveValidate(sql)){
entity.setStatus(SharingConstants.drafStatusKey);
//save
sno = sql.save(entity,SharingConstants.saveDocument,SharingConstants.sharing,oldStatus);
Log.info(getClass(), sno + " status:"+this.getStatusName());
Log.info(getClass(), sno + " save finished");
this.setSno(sno);
entity=sql.getSharing(sno,"</p>");
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
con.commit();
if (upload != null)
SharingUtil.getFile(upload, this.getUploadFileName(), sno,
SharingConstants.sharing);
Log.info(getClass(), "-----Save end-----");
isValidate=true;
result = SUCCESS;
}else{
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}
}else{
if (status.equals(SharingConstants.deployStatusKey)){//deploy
if (this.lengthValidate() && isValidate(SharingConstants.Deployed,sql)) {
SharingEntity shEntity=sql.getSharing(sno,"</p>");
entity.setAlertSite(shEntity.getAlertSite());
entity.setAlertDept(shEntity.getAlertDept());
entity.setDeployDept(shEntity.getDeployDept());
entity.setDeploySite(shEntity.getDeploySite());
entity.setDSite(shEntity.getDSite());
entity.setDDept(shEntity.getDDept());
//Start CR-2014-01727 Kevin
entity.setAlertCopy(shEntity.getAlertCopy());
entity.setDeployCopy(shEntity.getDeployCopy());
//End CR-2014-01727 Kevin
sno=sql.save(entity,SharingConstants.saveDocument,SharingConstants.sharing,oldStatus);
this.setSno(sno);
entity=sql.getSharing(sno,"</p>");
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
con.commit();
if (upload != null)
SharingUtil.getFile(upload, this.getUploadFileName(), sno,
SharingConstants.sharing);
Log.info(getClass(), "-----Save end-----");
isValidate=true;
result = SUCCESS;
}else{
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}
}else{
if (this.lengthValidate() && isSaveValidate(sql)) {
sno=sql.save(entity,SharingConstants.saveDocument,SharingConstants.sharing,oldStatus);
this.setSno(sno);
entity=sql.getSharing(sno,"</p>");
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
con.commit();
if (upload != null)
SharingUtil.getFile(upload, this.getUploadFileName(), sno,SharingConstants.sharing);
Log.info(getClass(), "-----Save end-----");
isValidate=true;
result = SUCCESS;
}else{
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}
}
}
}
}
if (!tp.equals("Exit")){
isValidate=false;
}
} catch (SizeLimitExceededException e) {
Log.info(this.getClass(), "SizeLimitExceededException:" + e.getMessage());
mess.add("SizeLimitExceededException:"+e.getMessage());
this.setStatusName(SharingConstants.New);
result=INPUT;
if (con!=null) con.close();
} catch (IOException e) {
Log.info(this.getClass(), "IOException:" + e.getMessage());
mess.add("IOException:"+e.getMessage());
this.setStatusName(SharingConstants.New);
result=INPUT;
if (con!=null) con.close();
} catch (FileUploadException e) {
Log.info(this.getClass(), "FileUploadException:" + e.getMessage());
// this.addActionError("Exception:"+e.getMessage());
mess.add("FileUploadException:"+e.getMessage());
this.setStatusName(SharingConstants.New);
result=INPUT;
if (con!=null) con.close();
} catch (Exception e) {
Log.info(this.getClass(), "Save exception:" + e.getMessage());
mess.add("Exception:"+e.getMessage());
this.setStatusName(SharingConstants.New);
result=INPUT;
// this.addActionError("Exception:"+e.getMessage());
if (con!=null) con.close();
}finally{
// this.setEntityDesc(sql,sSql);
// this.setEntity(entity);
//
// init(sql);
// isValidate=false;
if (con!=null) con.close();
}
return result;
}
private String urgency="";
public String geturgency() {
return urgency;
}
public void seturgency(String urgency) {
this.urgency = urgency;
}
}
I think i supposed to get the value from the jsp going to my action but not doing what im expecting.
Note: there's other textfield and dropdown i remove on the code above all of that is working except to the urgency dropdown that i added.
Also no exception or error found on the console on debugging mode
Your urgency setter names are incorrect; they should follow the JavaBean naming convention and be setUrgency/getUrgency.
Unrelated:
The action method should be named save to follow Java naming convention.
All parameters should be retrieved via setters (or ModelDriven), there is no need to access the action context here.
Most of your exception handling could be handled with a single multi-catch.
This action does far, far too much in a single method: refactor.
In general, setters should just set. If a setter is doing much more than setting it should have a more-obvious name.
There's more, but that's enough for now :)
I'm very new in spring development because I'm not a back developer.
I create a back to manage sports training.
I has several times a TransactionSystemException like
Exceptionorg.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
I don't understand what it mean.
I have a class Person who contains a Coordinates object on #OneToOne relation.
Each class have a Service class that has a method of adding.
In PersonService's add method, I call the Coordinates add method which save and return saved object.
This is the add method of PersonClass
public ResponseService<ObjectCreatedModel<UUID, PersonneMorale>> add(PersonneMorale personneMorale) {
String messageErreur = TAG + " - add - ";
StatusReturn status = StatusReturn.ERROR;
String message = null;
ObjectCreatedModel<UUID, PersonneMorale> objectCreatedModel = null;
if (personneMorale != null) {
if (personneMorale.getId() == null) {
personneMorale.setId(UUID.randomUUID());
try {
// Gestion des coordonnees
ResponseService<ObjectCreatedModel<UUID, Coordonnees>> responseServiceCoordonnees =
coordonneesService.add(personneMorale.getCoordonnees());
if (responseServiceCoordonnees.isSuccess() || responseServiceCoordonnees.exist()) {
ResponseService<Coordonnees> responseServiceCoordonneesGet = coordonneesService
.getOne(responseServiceCoordonnees.getObjectReturn().getId());
Coordonnees coordonnees = responseServiceCoordonneesGet.getObjectReturn();
personneMorale.setCoordonnees(coordonnees);
personneMorale = personneMoraleRepository.save(personneMorale);
if (personneMorale != null) {
status = StatusReturn.SUCCESS;
objectCreatedModel = new ObjectCreatedModel<>(personneMorale.getId(), null);
} else {
message = messageErreur + StringResource.E_OCCURRED;
}
} else {
status = responseServiceCoordonnees.getStatusReturn();
message = responseServiceCoordonnees.getMessage();
}
} catch (ConstraintViolationException violationException) {
status = StatusReturn.EXCEPTION;
message = messageErreur + ConstraintViolationReader.extractException(violationException);
} catch (Exception ex) {
status = StatusReturn.EXCEPTION;
message = messageErreur + ex.toString();
}
} else {
message = messageErreur + StringResource.E_MUST_NULL;
}
} else {
message = messageErreur + StringResource.E_SET_PARAMETER;
}
return new ResponseService<>(status, message, objectCreatedModel);
}
This is the add method of CoordinatesService
public ResponseService<ObjectCreatedModel<UUID, Coordonnees>> add(Coordonnees coordonnees) {
StatusReturn status = StatusReturn.ERROR;
String message = "";
ObjectCreatedModel<UUID, Coordonnees> objectCreatedModel = null;
if (coordonnees != null) {
if (coordonnees.getIdCoordonnees() == null) {
try {
coordonnees.setIdCoordonnees(UUID.randomUUID());
Coordonnees coordonneesBase = coordonneesRepository.save(coordonnees);
if (coordonneesBase != null) {
status = StatusReturn.SUCCESS;
objectCreatedModel = new ObjectCreatedModel<>(coordonneesBase.getIdCoordonnees(), null);
} else {
message = StringResource.E_ERROR_OCCURRED;
}
} catch (ConstraintViolationException violationException) {
status = StatusReturn.EXCEPTION;
message = "Exception" + ConstraintViolationReader.extractException(violationException);
} catch (Exception ex) {
status = StatusReturn.EXCEPTION;
message = "Exception" + ex.toString();
}
} else {
message = "Coordonnées" + ErrorsString.ERROR_COMMON_ID_MUST_BE_EMPTY;
}
} else {
message = ErrorsString.ERROR_COORDINATES_MANDATORY;
}
return new ResponseService<>(status, message, objectCreatedModel);
}
The error occurs when CoordinatesService try to save coordinates and pass to the catch (Exception e)
Could you help me to understand what Transaction error mean with an example like my code please ?
I created a java class called Executar_Query_Bd_Multiplos_Resultados in this class as the parameter for the Conectar method 2 values (int Integer1, int Integer2) of integer type.
These values are received by the query:
"SELECT DS_ESTRATEGY, STRID_ID" +
"FROM TB_BKOFFICE_ESTRATEGY" +
"WHERE IN_STRATEGY_ID IN (" + Istrategy1 + "," + Istrategy2 + ")";
The result of the above query is stored in the variable ls_command.
In the Executar_Query_Bd_Multiplos_Resultados_Test class I make the method call (Connect) and step 2 parameters (179, 319) and command to print on the screen the variable of type String codEstrategies.
But Eclipse only displays 1 result on the console. The query should bring 2 results and not 1. Here is the code for the Java classes and the result of the query executed in Oracle SQL Developer.
public class Executar_Query_Bd_Multiplos_Resultados_Test {
#Before
public void setUp() throws Exception {
Executar_Query_Bd_Multiplos_Resultados qr_2 = new Executar_Query_Bd_Multiplos_Resultados();
String codEstrategias = qr_2.Conectar(179, 319);
System.out.println("Estratégias: " + codEstrategias);
}
#After
public void tearDown() throws Exception {
}
#Test
public void test() {
}
}
public class Executar_Query_Bd_Multiplos_Resultados {
//Variáveis de BD
Connection conOracle = null;
Statement stmtOracle = null;
ResultSet rsetOracle = null;
public String Conectar(int Id_Estrategia1, int Id_Estrategia2) {
String retorno = "#;-1;#";
Boolean lb_continuar = true;
//StringBuilder ls_comando = new StringBuilder();
String ls_comando = new String();
try {
System.out.println("Conectando ao banco de dados Oracle...");
String url = "";
try {
//conectando aos bancos de dados
Class.forName("oracle.jdbc.driver.OracleDriver");
url = "jdbc:oracle:thin:#10.5.12.116:1521:desenv01";
DriverManager.setLoginTimeout(10);
conOracle = (Connection) DriverManager.getConnection(url, "bkofficeadm", "bkofficeadmdesenv01");
} catch (SQLException e) {
System.out.println("falha SQL >> " + e.getMessage());
} catch (Exception e) {
//System.out.println("falha geral >> " + e.getMessage());
e.printStackTrace();
lb_continuar = false;
}
//String teste = "'BKO - Rep Conectividade'";
if (lb_continuar) {
System.err.println("Preparando comando...");
System.out.println("");
ls_comando = "SELECT DS_ESTRATEGIA, ID_ESTRATEGIA"+
" FROM TB_BKOFFICE_ESTRATEGIA"+
" WHERE ID_ESTRATEGIA IN (" + Id_Estrategia1 + ", " + Id_Estrategia2 + ")";
System.out.println(ls_comando);
stmtOracle = conOracle.createStatement();
stmtOracle.setQueryTimeout(10);
rsetOracle = stmtOracle.executeQuery(ls_comando.replaceAll("\n", " ").trim());
if(rsetOracle.next()) {
retorno = rsetOracle.getString(1);
}
rsetOracle.close();
stmtOracle.close();
/*
Para comandos de Insert, Delete, ou Update
--------------------------------------------------------
stmtOracle = conOracle.createStatement();
stmtOracle.setQueryTimeout(10);
stmtOracle.execute(variavel_comando.toString());
conOracle.commit();
stmtOracle.close();
*/
}
} catch (Exception ex) {
System.out.println("Erro - " + ex.getMessage());
} finally {
try {
if (rsetOracle != null) {
rsetOracle.close();
}
} catch (Exception e) {
System.out.println("Erro ao fechar rset - " + e.getMessage());
}
try {
if (stmtOracle != null) {
stmtOracle.close();
}
} catch (Exception e) {
System.out.println("Erro ao fechar stmt - " + e.getMessage());
}
try {
if (conOracle != null && !conOracle.isClosed()) {
conOracle.close();
}
if (conOracle != null && !conOracle.isClosed()) {
conOracle.close();
}
} catch (Exception e) {
System.out.println("Erro ao fechar con - " + e.getMessage());
}
}
return retorno;
}
}
Output from SQL Devleoper query:
Output from Eclipse console:
You're doing this
if(rsetOracle.next()) {
retorno = rsetOracle.getString(1);
}
This runs once
Consider while instead:
List<String> retornos = new ArrayList<>();
while(rsetOracle.next()) {
retornos.add(rsetOracle.getString(1));
}
This will run until you're out of rows.
If something like this happens in the future, you'll want to modify your query to select count(*) ... and verify you get the same result in both the database workbench and your javacode. Then you'll at least know you've got the right query, and it's your presentation that's failing.
Note:
I understand this question is indeed a duplicate of other questions. However, those are difficult to search. I would propose this be a canonical answer.
I'm using a method to save a object in database, see:
#Transactional(propagation = Propagation.REQUIRED)
public void movimentarCaixa(String descricao,
AbstractBean donoCaixa, FormaPagamento formaPagamento, HistoricoPagamento historicoPagamento, double valor) {
try {
HistoricoCaixa historicoCaixa;
if (donoCaixa instanceof Dentista) {
logger.info("Iniciando movimentacao caixa para Dentista. Valor: "+valor);
historicoCaixa = new HistoricoCaixaDentista();
((Dentista) donoCaixa).setCaixaSaldoAtual(((Dentista) donoCaixa).getCaixaSaldoAtual()
+ valor);
((HistoricoCaixaDentista) historicoCaixa).setDentista((Dentista) donoCaixa);
} else if (donoCaixa instanceof Paciente) {
logger.info("Iniciando movimentacao caixa para Paciente. Valor: "+valor);
historicoCaixa = new HistoricoCaixaPaciente();
((Paciente) donoCaixa).setCaixaSaldoAtual(((Paciente) donoCaixa).getCaixaSaldoAtual()
+ valor);
((HistoricoCaixaPaciente) historicoCaixa).setPaciente((Paciente) donoCaixa);
} else if (donoCaixa instanceof Clinica) {
logger.info("Iniciando movimentacao caixa para Clinica. Valor: "+valor);
historicoCaixa = new HistoricoCaixaClinica();
Clinica clinica = (Clinica) donoCaixa;
if (formaPagamento == null || formaPagamento.getCodigo().equals("DINHEIRO")){
clinica.setSaldoDinheiro(clinica.getSaldoDinheiro() + valor);
} else if (formaPagamento.getCodigo().equals("CHEQUE")) {
clinica.setSaldoCheque(clinica.getSaldoCheque() + valor);
} else if (formaPagamento.getCodigo().equals("DEBITO")) {
clinica.setSaldoDebito(clinica.getSaldoDebito() + valor);
} else if (formaPagamento.getCodigo().equals("CREDITO")) {
clinica.setSaldoCredito(clinica.getSaldoCredito() + valor);
}
((HistoricoCaixaClinica) historicoCaixa).setClinica((Clinica) donoCaixa);
} else {
throw new MyException(
"O parametro 'donoCaixa' deve ser do tipo Dentista, Paciente ou Clinica");
}
historicoCaixa.setDataHora(historicoPagamento.getDataHora());
historicoCaixa.setDescricao(descricao);
historicoCaixa.setFormaPagamento(formaPagamento);
historicoCaixa.setHistoricoPagamento(historicoPagamento);
historicoCaixa.setUsuario((Usuario) SessionContext.getInstance().getUsuarioLogado());
historicoCaixa.setValor(valor);
this.getDao().save(historicoCaixa);
} catch (Exception e) {
e.printStackTrace();
}
}
I call this method twice, in the first time the variable "historicoCaixa" receives "new HistoricoCaixaPaciente()" instance and in second time this same variable receives "new HistoricoCaixaClinica()". The problem is that in second call i got error:
Caused by: java.lang.IllegalArgumentException: Removing a detached instance br.com.odontonew.financeiro.bean.HistoricoCaixaClinica#94
I imagine that JPA is trying to remove HistoricoCaixaClinica#94 but i don't want this, how can i avoid it ?
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I created a website with JSP and Java, it simply displays a form (it's a user registration form) where the user can fill it, then I want it to be stored in a database.
I installed Eclipse, Tomcat (to host on localhost 8080) and Wampserver (to have phpmyadmin and my SQL database).
I've tried to create an ORM (Object-relational mapping), so when the client submits the form, it sends the datas to my ORM, my ORM then stores the datas in my database.
The issue is, when the user submit submits the form, my table is created (I can see it on phpmyAdmin), so it's very good. But it crashes on my website and creates an error
HTTP500, java.lang.NullPointerException.
It says the problem is on
com.jweb.bdd.Orm.Perform(Orm.java:139)
Here is my code in my CreateClient.java file, this java file handles the servlet of my registration form:
public class CreationClient extends HttpServlet {
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
[...]
String lastName= request.getParameter( CHAMP_LASTNAME);
String Name= request.getParameter( CHAMP_NAME);
String mailAdress = request.getParameter( CHAMP_MAILADRESS);
String phoneNumber= request.getParameter( CHAMP_PHONENUMBER);
String login= request.getParameter( CHAMP_LOGIN);
[...]
Orm orm = new Orm();
String[] field = {"login", "firstName", "lastName", "mailAdress", "adress", "phoneNumber", "password"};
String[] values = {login, firstName, lastName, mailAdress, adress, phoneNumber, password};
orm.Insert("client", field);
orm.Values(values);
orm.Perform();
orm.CloseConnection();
[...]
}
}
Here is my Perfom() function in my ORM class:
public void Perform(){
ResultSet rst = null;
if (select != null){
if (from != null && where != null){
try {
rst = statement.executeQuery(select + from + where);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
int i = 0;
while (rst.next()){
res[i] = rst.getString(0) + ":" + rst.getString(1)+ ":" + rst.getString(3) + ":" + rst.getString(4) +":" + rst.getString(5) + ":" + rst.getString(6)+ ":" + rst.getString(7) + ";";
i++;
}
} catch (SQLException e){
e.printStackTrace();
}
}
}
else if (insert != null){
if (values != null){
try {
// statement = connexion.creatStatemnt();
int res = statement.executeUpdate(insert + values);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
try {
rst.close();
} catch (SQLException ignore){
}
if ( statement != null ) {
try {
statement.close();
} catch ( SQLException ignore ) {
}
}
}
And the error on the line 139 is the int res = statement.executeUpdate(insert + values); :
else if (insert != null){
if (values != null){
try {
int res = statement.executeUpdate(insert + values);
} catch (SQLException e) {
e.printStackTrace();
}
}
Do you have any idea how to fix this issue of NullPointer?
Thanks.
You need to initialize your statement object, In your code you used statement.executeQuery() but not statement = connection.createStatement() initialize statement object.