0

I have java code which retrieve some data from MySQL with appropriate code in netbeans.The code is below. I want to do multi query such as for example finding total number of products and so on.could you help me please. thanks in advance

 import java.sql.*;


public class JavaMysqlSelectExample
{

  public static void main(String[] args)
  {
try
{

  String myDriver = "com.mysql.jdbc.Driver";
  String myUrl = "jdbc:mysql://localhost/sample";
  Class.forName(myDriver);
  Connection conn = DriverManager.getConnection(myUrl, "root", "mypasscode1");


  String query = "SELECT * FROM products";
  Statement st = conn.createStatement();


  ResultSet rs = st.executeQuery(query);

  while (rs.next()==true)
  {
    int code = rs.getInt("code");
    String productname = rs.getString("product_name");
    String producttype = rs.getString("product_type");
    System.out.format(" %d, %s, %s\n", code, productname, producttype);
  }
  st.close();
}
catch (Exception e)
{
  System.err.println("Error message: ");
  System.err.println(e.getMessage());
}

} }

developer
  • 25
  • 1
  • 11

1 Answers1

0

Create another statement then query again. Don't close the connection to database until you finish your job. Until user disconnects, db connection can be alive.(Best case)

Database connection is consuming job for code if you open connection for each request, it will cause a bad performance.

Select count(1) from products : gives you the total number of products

OR

long counter = 0;
while (rs.next()==true)
{
    int code = rs.getInt("code");
    counter++;
    String productname = rs.getString("product_name");
    String producttype = rs.getString("product_type");
    System.out.format(" %d, %s, %s\n", code, productname, producttype);
}

System.out.println("Total Product Count : " + counter);
Gurkan İlleez
  • 1,503
  • 1
  • 10
  • 12