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) { }
}
}