Hi, I am biginer to java. I need to make a class method that retrieve specific row values from database (using ID), and then to make new class instance using those values (as field properties). I wrote code for the first part(getting row value from ID), but I need help with second part (making new class instance). Here is the code:

import java.sql.*;


public class Products {
private int ProductID;
private String name;
private String category;
private Double price;
public void setId(int ProductID) { this. ProductID = ProductID; }
public int getId() { return this.ProductID; }
public void setName(String name) { this.name = name; }
public String getName() { return this.name; }
public void setCategory(String category) { this. category = category; }
public String getcategory () { return this.category; }
public void setPrice(double price) { this.price = price; }
public double getCijena() { return this.price; }

public Products(int ProductID, String name, String category, Double price)
{
    this.ProductID = ProductID;
    this.name = name;
    this.category = category;
    this.price = price;
  }

public static void getFromId(int productID)
{
Connection conn = null;
   {
try
    {
      Class.forName ("com.mysql.jdbc.Driver").newInstance ();
          conn = DriverManager.getConnection ("jdbc:mysql://localhost/prodaja", "root", "");
        System.out.println(conn.isClosed());
    }
catch(Exception ex)
{ 
System.out.println("Connection not established"); 
}
 try
{
 Statement st = conn.createStatement();
    st.executeQuery("select * from products WHERE ID_product="+productID);
    ResultSet rs = st.getResultSet();
    while (rs.next()) 
    {
        int IdP = rs.getInt(1);
        System.out.println("id="+IDP);
        String Pname = rs.getString(2);
        String Pcategory = rs.getString(3);
        Double Pprice = rs.getDouble(4);
        System.out.println("Product name="+ Pname);
        System.out.println("Product categoty="+ Pcategory);
        System.out.println("Price="+ Pprice);
    }
}
   catch (SQLException s){
  System.out.println("SQL statement not executed!");
}

finally {
try
    {
    if(conn!=null && !conn.isClosed())
        conn.close();
    System.out.println(conn.isClosed());
    }
catch(Exception ex) { }

 }
}

By line 52 you have variables containing the id, name, category and price.
At line 18 you have a constructor that takes id, name, category and price and creates a Products instance.
So all you need to do is call the constructor passing the values.. easy peasy!

ps: Each instance of your class represents one Product, so your code will read better if you call it Product rather than Products.

Maybe this will sound like a stupid question, but did you mean like this:

public Products(int ProductID, String name, String category, Double price)
{
    this.ProductID = IdP;
    this.name = Pname;
    this.category = Pcategory;
    this.price = Pprice;
  }

No, no need to do anything like that.
You have a perfectly good constructor already. You just have to call it from around line 52. Check out how to calla constructor to create a new instance of a class.

Is this correct:

Products p= new Products(IdP,Pname,Pcategory,Pprice);

yes! It really is that easy!
Now you have to decide what you are going to do with that new Products instance.

Thank you. Now this method(getFomId) should return this new object(class instance) which contains in its fields values retrieved from that database row. Any suggestions?

Maybe I didn't phrase it correctly in my previous post(my English is not so well). I need now to make this method(getFromId) return this newly created class instance(object), with its field values (retrieved from database row). I hope this sounds better.

Some hints:

  • The word "void" is how you say "this method does not return anything."
  • Returning the right thing is actually very easy. You're almost there.
  • The trick will be that every path through the method will need to either return something or throw an exception. Using "return null;" in the right place(s) might be useful.

But method Return could be used only once through the method GetFromId, isn't this right?

A method can have more than one return statement (eg it may return null if there is an error). You must ensure that no matter which if tests and loops are executed, it always ends up by executing a return statement.

People will tell you that it's best to have only one "return" statement in a method. There is a lot to be said for that, but it is not mandatory with respect to making the program work.

If you don't get all the right "return" and exception throwing things in the right places, the compiler will tell you. So don't worry about what I said about "return null;" unless/until you get a certain compiler error... And then you might find my comment helpful. ;-)

Some hints:

  • The word "void" is how you say "this method does not return anything."
  • Returning the right thing is actually very easy. You're almost there.
  • The trick will be that every path through the method will need to either return something or throw an exception. Using "return null;" in the right place(s) might be useful.

I changed "void" to return type. Do you mean to check if inserted ID is valid?

Some hints:

  • The word "void" is how you say "this method does not return anything."
  • Returning the right thing is actually very easy. You're almost there.
  • The trick will be that every path through the method will need to either return something or throw an exception. Using "return null;" in the right place(s) might be useful.

What exactly do you mean by

...every path through the method...

What exactly do you mean by "every path must return a value"?

If a method returns Product (rather than void) then every time it executes it must return an instance of Product, or null, or it may throw an exception. It cannot exit without doing one of those. In fact, it won't compile unless the compiler is sure that it will always in all cases do one of those.

The easiest way to ensure this is to have the "return" statement be the last statement in the method.

Don't worry about this rule too much. When you violate it, the compiler tells you, and you will have to fix it.

I think I solved it. I want to thank everyone who participated.

public static Product getFromId(int productID)
{
Connection conn = null;
Product p = null;
   {
try
    {
      Class.forName ("com.mysql.jdbc.Driver").newInstance ();
          conn = DriverManager.getConnection ("jdbc:mysql://localhost/prodaja", "root", "");
        System.out.println(conn.isClosed());
    }
catch(Exception ex)
{ 
System.out.println("Connection not established"); 
}
 try
{
 Statement st = conn.createStatement();
    st.executeQuery("select * from products WHERE ID_product="+productID);
    ResultSet rs = st.getResultSet();
    while (rs.next()) 
    {
        int IdP = rs.getInt(1);
        String Pname = rs.getString(2);
        String Pcategory = rs.getString(3);
        Double Pprice = rs.getDouble(4);
        p=new Product(IdP, Pname, Pcategory, Pprice);
         
    }
}
   catch (SQLException s)
{ 
  System.out.println("SQL statement not executed!");
}

finally {
try
    {
    if(conn!=null && !conn.isClosed())
        conn.close();
    System.out.println(conn.isClosed());
    }
catch(Exception ex) { }
return p;
}
}
}
}

And for the main class (code for print not necessary):

public class Sales {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Product p = Product.getFromId(1001);

if(p == null) {

    System.out.println("No products in DB!");

    } else {

    System.out.println("Id: " + p.getId()+ " Name: " + p.getName()+" Opis: " + p.getCategory()+" Price: " + p.getPrice());

    }

} 
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.