简体   繁体   中英

JDBC MySQL new Insert not detected

I'm working inn a java server using a Mysql dataBase and a jdbc connection

The problem comes when I try to do the following steps

1.Start the server

2.Insert manually (using phmypadmin) a new record in the database.

3.Select the records using the jdbc api

I only get the records that already were in the DB, not the new one.

Here's my connection :

 public JDBCMySQL(String nomFitxerPropietats) throws Exception {
        if (nomFitxerPropietats == null) {
            nomFitxerPropietats = "jdbcMysql.txt";
        }
        Properties props = new Properties();
        try {
            props.load(new FileReader(nomFitxerPropietats));
        } catch (FileNotFoundException ex) {
            throw new Exception("No es troba fitxer de propietats", ex);
        } catch (IOException ex) {
            throw new Exception("Error en carregar fitxer de propietats", ex);
        }
        String driver = props.getProperty("driver");
        if (driver == null && System.getProperty("java.version").compareTo("1.6") < 0) {
            throw new Exception("La versió de Java obliga a definir la propietat driver dins el fitxer de propietats");
        }
        String url = props.getProperty("url");
        if (url == null) {
            throw new Exception("Manca la propietat url en el fitxer de propietats");
        }
        String user = props.getProperty("user");
        String password = props.getProperty("password");
        // No controlem !=null per què hi ha SGBDR que permeten no indicar user/contrasenya (MsAccess)
        try {
            if (driver != null) {
                Class.forName(driver);
            }
            con = DriverManager.getConnection(url, user, password);
            con.setAutoCommit(false);
        } catch (SQLException ex) {
            throw new Exception("No es pot establir connexió", ex);
        } catch (ClassNotFoundException ex) {
            throw new Exception("No es pot carregar la classe " + driver);
        }

    }

And this is the function I use to retrieve my records:

  @Override
    public List<Cita> getCitas(int sesID) {
    List<Cita> citas = new ArrayList<Cita>();
     try {

     Statement st = null;
    ResultSet rs = null;

       String consulta = "  select iii.estatinforme,s.NUMERO,c.diahora, s.PERIT_NO,s.INFORME_NO,s.POLISSA_ID,s.DATAASSIGNACIO,s.DATAOBERTURA,s.DATATANCAMENT,s.DESCRIPCIOSINISTRE,s.TIPUSSINISTRE,s.ESTATSINISTRE,s.polissa_id,p.municipi from SINISTRE s join POLISSA p on (s.polissa_id = p.ID_POLISSA) join PERIT pe on ( pe.NUMERO = s.PERIT_NO) join CITA c on (c.sinistre_id = s.numero) left join INFORMEPERICIAL iii on (c.sinistre_id=iii.sinistre_id) where ( s.PERIT_NO = ? and (iii.ESTATINFORME = 'PENDENT'  or iii.ESTATINFORME is null  or DATE_FORMAT(c.diahora, '%Y-%m-%d') = CURDATE()   )) order by c.diahora ";

       PreparedStatement pstmt = con.prepareStatement(consulta);

       pstmt.setInt(1, sesID);

      rs =  pstmt.executeQuery();

        while (rs.next()) {
          //handling my reads...

        }
         pstmt.close();
           rs.close();
  } catch (SQLException ex) {
      Logger.getLogger(JDBCMySQL.class.getName()).log(Level.SEVERE, null, ex);
  }

    return citas;
}

I suspect that it has nothing to do with the prepared statement or the query because, after I stop the server and start it again, the new is retrieved with the function GetCitas().

Edited: the config file I'm using (jdbcMysql.txt) :

url=jdbc:mysql://MyIP:3306/mydb

user=myuser

password=mypass

All in all this seems to be an issue of Transaction Isolation .

Basically, as long as some transaction has not commited inserted or updated data, you cannot see that in another program.

Just the same, as long as your transaction is open, you'll always receive the same state your database had when your transaction started.

Having set autocommit=false you started that transaction very early on in your program and as long as you don't commit() your transaction, you'll see same snapshot (at least with default mysql transaction isolation REPEATABLE READ in place)

That's why manually commit() ing your connection before your select works.

consistent read

A read operation that uses snapshot information to present query results based on a point in time, regardless of changes performed by other transactions running at the same time. If queried data has been changed by another transaction, the original data is reconstructed based on the contents of the undo log. This technique avoids some of the locking issues that can reduce concurrency by forcing transactions to wait for other transactions to finish.

On another topic: Your code could greatly benefit from some cleaning - see the following implementation of getCitas using try-with-resource:

    @Override
    public List<Cita> getCitas(int sesID) {
      List<Cita> citas = new ArrayList<Cita>();
      String consulta = "select iii.estatinforme,s.NUMERO, [...]";
      try (PreparedStatement pstmt = con.prepareStatement()) {
          pstmt.setInt(1, sesID);
          try(ResultSet rs =  pstmt.executeQuery()) {
              while (rs.next()) {
                  //handling my reads...
              }
          }
      } //Closing happend automatically! Even in case of an error!
      catch (SQLException ex) {
          Logger.getLogger(JDBCMySQL.class.getName()).log(Level.SEVERE, null, ex);
      }     
      return citas;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM