Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve result set of a query from MySQL in java

I am already connected to my database:

Connection con = DriverManager.getConnection(
    "jdbc:mysql://instance23389.db.xeround.com:15296/Inventory","user","password");
PreparedStatement Statement = con.prepareStatement("Select * from inventory");
ResultSet result = Statement.executeQuery();
while(result.next()) {
    //What to put here?
}

This is the arraylist I want stored in that database:

static ArrayList<Product> Chart=new ArrayList<Product>();

And that has these objects stored in the arraylist:

double Total;
String name;
double quantity;
String unit;
double ProductPrice;

What is the general code I need to use to get the arraylist to be stored in the MySQL database? What is the general code I need to use to get the arraylist out of the MySQL database?

like image 331
Vincent Taglia Avatar asked Dec 06 '22 13:12

Vincent Taglia


2 Answers

This is a template of what to use for retrieving & populating the Arraylist productList

while (result.next()) {

    Product product = new Product();

    product.setTotal(result.getDouble("Total"));
    product.setName(result.getString("Name"));
    // etc.

    productList.add(product);
}

In the meantime, I invite you to have a look at:

http://www.jdbc-tutorial.com/

like image 196
Reimeus Avatar answered Dec 10 '22 10:12

Reimeus


Your question is not very clear, but I am guessing that you want something like:

List<Product> products = new ArrayList<Product>();

String host = "instance23389.db.xeround.com";
int port = 15296;
String dbName = "Inventory";
String url = "jdbc:mysql://" + host + ":" + port + "/" + dbName;

Connection con = null;
PreparedStatement stmt = null;

try {

  con = DriverManager.getConnection(url, "user","password");
  stmt = con.prepareStatement("select * from inventory");
  ResultSet result = stmt.executeQuery();
  while(result.next()) {
    Product prod = new Product();
    prod.setTotal(result.getDouble("total"));
    prod.setName(result.getString("name"));
    prod.setQuantity(result.getDouble("quantity"));
    prod.setUnit(result.getString("unit"));
    prod.setProductPrice(result.getDouble("product_price"));
    products.add(prod);
  }
} finally {
  if (stmt != null) {
    try { 
      stmt.close();
    } catch (SQLException ex) {
    }
  }
  if (con != null) {
    try { 
      con.close();
    } catch (SQLException ex) {
    }
  }
}
return products;
like image 41
Binil Thomas Avatar answered Dec 10 '22 11:12

Binil Thomas