2013-05-15 9 views
5

Ho avuto difficoltà a cercare di capirlo. Per prima cosa ho un metodo insertProduct(Product p) che dovrebbe controllare se esiste un prodotto con il codice specificato nel database. In tal caso, questo metodo mostrerà un messaggio di errore. Altrimenti, dovrebbe aggiungere il prodotto al database e stamparlo sulla console. Non sono sicuro se lo sto facendo correttamente.Java SQL Exception Stato del cursore non valido - nessuna riga corrente

In secondo luogo, il metodo deleteProduct(Product p) deve eliminare il prodotto che è stato aggiunto dal metodo insertProduct. Il problema è che continuo a ricevere un'eccezione SQL quando provo ad aggiungere il prodotto e quindi il metodo continua a eliminare i prodotti presenti nel database uno per uno ogni volta che il programma viene eseguito finché non ne viene lasciato uno. Non sono sicuro di cosa non vada in entrambi questi metodi.

Console in uscita:

Derby has been started. 

Product list: 
bvbn Murach's Beginning Visual Basic .NET  $49.50 
cshp Murach's C#         $49.50 
java Murach's Beginning Java      $49.50 
jsps Murach's Java Servlets and JSP    $49.50 
mcb2 Murach's Mainframe COBOL     $59.50 
sqls Murach's SQL for SQL Server     $49.50 
zjcl Murach's OS/390 and z/OS JCL    $62.50 

First product: 
bvbn Murach's Beginning Visual Basic .NET  $49.50 

Last product: 
zjcl Murach's OS/390 and z/OS JCL    $62.50 

Product by code: cshp 
cshp Murach's C#         $49.50 

Insert test: 
java.sql.SQLException: Invalid cursor state - no current row. 
Product list: 
bvbn Murach's Beginning Visual Basic .NET  $49.50 
cshp Murach's C#         $49.50 
java Murach's Beginning Java      $49.50 
jsps Murach's Java Servlets and JSP    $49.50 
mcb2 Murach's Mainframe COBOL     $59.50 
sqls Murach's SQL for SQL Server     $49.50 
zjcl Murach's OS/390 and z/OS JCL    $62.50 

Delete test: 
zjcl Murach's OS/390 and z/OS JCL    $62.50 

Product list: 
bvbn Murach's Beginning Visual Basic .NET  $49.50 
cshp Murach's C#         $49.50 
java Murach's Beginning Java      $49.50 
jsps Murach's Java Servlets and JSP    $49.50 
mcb2 Murach's Mainframe COBOL     $59.50 
sqls Murach's SQL for SQL Server     $49.50 

Derby has been shut down. 

Codice:

import java.sql.*; 

public class DBTesterApp 
{ 
private static Connection connection = null; 
private static Product p = null ; 
public static void main(String args[]) 
{ 
    // get the connection and start the Derby engine 
    connection = MurachDB.getConnection(); 
    if (connection != null) 
     System.out.println("Derby has been started.\n"); 

    // select data from database 
    printProducts(); 
    printFirstProduct(); 
    printLastProduct(); 
    printProductByCode("cshp"); 

    // modify data in the database 
    p = new Product("test", "Test Product", 49.50);   
    insertProduct(p); 
    printProducts(); 

    deleteProduct(p); 
    printProducts(); 

    // disconnect from the database 
    if (MurachDB.disconnect()) 
     System.out.println("Derby has been shut down.\n"); 
} 

public static void printProducts() 
{ 

    // Product p = null ; 
    try (Statement statement = connection.createStatement(); 
     ResultSet rs = statement.executeQuery("SELECT * FROM Products")) 
    {    


     System.out.println("Product list:"); 
     while(rs.next()) 
     { 
      String code = rs.getString("ProductCode"); 
      String description = rs.getString("Description"); 
      double price = rs.getDouble("Price"); 

     p = new Product(code, description, price); 

      printProduct(p); 
     } 
     System.out.println(); 
    } 
    catch(SQLException e) 
    { 
     e.printStackTrace(); // for debugging 
    } 
    } 

    public static void printFirstProduct() 
    { 

    try(Statement statement = connection.createStatement(
      ResultSet.TYPE_SCROLL_SENSITIVE, 
      ResultSet.CONCUR_UPDATABLE); 

     ResultSet rs = statement.executeQuery("SELECT * FROM Products")){ 

     System.out.println("First product:"); 

     rs.first(); 
     rs.last(); 

     if(rs.isFirst() == false){ 
      rs.previous(); 
     } 

     if(rs.isLast() == false){ 
      rs.next(); 
     } 

     rs.absolute(1); 
     String code = rs.getString(1); 
     String description = rs.getString(2); 
     double price = rs.getDouble(3); 

     p = new Product(code , description , price); 
     printProduct(p); 
     System.out.println(); 
    } 

    catch(SQLException e){ 
      e.printStackTrace(); 
     } 
    } 

public static void printLastProduct() 
{ 
    try(Statement statement = connection.createStatement(
      ResultSet.TYPE_SCROLL_SENSITIVE, 
      ResultSet.CONCUR_UPDATABLE); 

     ResultSet rs = statement.executeQuery("SELECT * FROM Products")){ 
     System.out.println("Last product:"); 


     rs.first(); 
     rs.last(); 

     if(rs.isFirst() == false){ 
      rs.previous(); 
     } 

     if(rs.isLast() == false){ 
      rs.next(); 
     } 

     rs.absolute(7); 
     String code = rs.getString(1); 
     String description = rs.getString(2); 
     double price = rs.getDouble(3); 

     p = new Product(code, description, price); 
     printProduct(p); 
     System.out.println(); 



    } 

    catch(SQLException e){ 
     e.printStackTrace(); 
    } 
} 

    public static void printProductByCode(String productCode) 
    { 

     String sql = 
      "SELECT ProductCode, Description, Price " + 
      "FROM Products " +  
      "WHERE ProductCode = ?"; 

    try(PreparedStatement ps = connection.prepareStatement(sql);){ 

     ps.setString(1, productCode); 
     ResultSet rs = ps.executeQuery(); 

     if(rs.next()){ 
     String description = rs.getString("Description"); 
     double price = rs.getDouble("Price"); 
     p = new Product(productCode, description, price); 
     System.out.println("Product by code: " + productCode); 
     printProduct(p); 
     } 
      else{ 
      rs.close(); 
       } 

    } 


    catch(SQLException e){ 
    System.err.println(e); 

    } 


    System.out.println(); 
    } 

    public static void insertProduct(Product p) 
    { 
    System.out.println("Insert test: "); 


    //check if product code exists in database 
    try(Statement statement = connection.createStatement(); 
     ResultSet rs = statement.executeQuery("SELECT * FROM Products")){ 

    String code = rs.getString(1); 


    if (p.getCode().equals(code)){ 
     System.out.println("Error: This product is already in the database!"); 
     } 


    else{ 
    String sql = 
      "INSERT INTO Products (productCode, Description, Price) " + 
      "VALUES (?, ?, ?)"; 

    try(PreparedStatement ps = connection.prepareStatement(sql)){ 


     ps.setString(1, p.getCode()); 
     ps.setString(2, p.getDescription()); 
     ps.setDouble(3, p.getPrice()); 
     ps.executeUpdate(); 
     } 


    catch(SQLException e){ 
      System.err.println(e); 
     } 


    } //end else 

     printProduct(p); 
    System.out.println(); 

    }//end try 


     catch(SQLException e){ 
     System.out.println(e); 
     } 
} 

private static void deleteProduct(Product p) 
{ 
    System.out.println("Delete test: "); 

    String sql = "DELETE FROM Products " + 
       "WHERE ProductCode = ?"; 

    try(PreparedStatement ps = connection.prepareStatement(sql)){ 
     ps.setString(1, p.getCode()); 
     ps.executeUpdate(); 

    } 

    catch(SQLException e){ 
     System.err.println(e); 
    } 
    // add code that deletes the specified product from the database 
    // if a product with the specified code doesn't exist, display an error message 

    printProduct(p); 
    System.out.println(); 
} 

// use this method to print a Product object on a single line 
private static void printProduct(Product p) 
{ 
    String productString = 
     StringUtils.padWithSpaces(p.getCode(), 8) + 
     StringUtils.padWithSpaces(p.getDescription(), 44) + 
     p.getFormattedPrice(); 

    System.out.println(productString); 
} 
} 

risposta

6

È necessario chiamare ResultSet.next() prima di poter recuperare un valore di colonna.

// check if product code exists in database 
try(Statement statement = connection.createStatement(); 
    ResultSet rs = statement.executeQuery("SELECT * FROM Products")){ 
if (rs.next()) // THIS is MISSING! 
    String code = rs.getString(1); 

Il codice di cui sopra sarebbe correre senza eccezioni, ma sarebbe ancora non riescono logicamente dal momento che si sta selezionando tutti i prodotti e solo controllando il codice per la prima fornita dal database. Il corretta modo per verificare se il prodotto è già esistente è

// check if product code exists in database 
try(Statement statement = connection.createStatement(); 
    ResultSet rs = statement.executeQuery(
     "SELECT * FROM Products WHERE ProductCode = '" + p.getCode() + "'")){ 
if (rs.next()) { 
    System.out.println("Error: This product is already in the database!"); 
    return; 
} 
+0

ho provato, ma ora ottengo questo: 'java.sql.SQLSyntaxErrorException: Colonna 'TEST' è o non è in alcun tabella nella elenca o appare all'interno di una specifica di join e non rientra nell'ambito della specifica di join o appare in una clausola HAVING e non è nella lista GROUP BY. Se questa è un'istruzione CREATE o ALTER TABLE, allora 'TEST' non è una colonna nella tabella di destinazione. – oxxi

+0

Ecco come ho cambiato il metodo: http://pastebin.com/wPBq0Jpf – oxxi

+0

Hai ancora mancato la rimozione di 'rs .getString (1); '. È appena sopra il punto in cui hai aggiunto 'rs.next()'. Controllando il resto –

0

nel metodo insertProduct, è necessario chiamare il metodo next() sul ResultSet prima di andare a prendere i dati da esso.

Problemi correlati