-1

I having a problem to run below Java code. I couldn't find the DB.java class.

ResultSet rs = DB.getConnection().createStatement().executeQuery("select * from products");
while(rs.next()){
    System.out.print(rs.getString("pid"));
    System.out.print(rs.getString("name"));
    System.out.print(rs.getString("price"));
    System.out.print(rs.getString("ava_qty"));
}

I'm using Glassfish server. Can someone help me to write the DB.java class?

dur
  • 15,689
  • 25
  • 79
  • 125
Russel
  • 29
  • 2
  • 7
  • you should be better off with posting an error message – Irf May 29 '17 at 08:36
  • Can you please add the purpose of the DB.java file. Do you want to achieve connection pooling? or just creating and returning new connection? Posting answer is something dependent on your expectation. – Sudhir Dhumal Jul 13 '17 at 08:58

1 Answers1

0

The getConnection() method is part of the DriverManager class. Initialize your drivermanager properly, as described in this post:

https://www.tutorialspoint.com/javaexamples/jdbc_dbconnection.htm

Example code for future reference:

import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) {
      try {
         Class.forName("org.apache.derby.jdbc.ClientDriver");
      } catch(ClassNotFoundException e) {
         System.out.println("Class not found "+ e);
      }
      System.out.println("JDBC Class found");
      int no_of_rows = 0;

      try {
         Connection con = DriverManager.getConnection (
            "jdbc:derby://localhost:1527/testDb","username", "password");  
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery ("SELECT * FROM employee");
         while (rs.next()) {
            no_of_rows++;
         }
         System.out.println("There are "+ no_of_rows + " record in the table");
      } catch(SQLException e){
         System.out.println("SQL exception occured" + e);
      }
   }
}
Martijn Burger
  • 7,315
  • 8
  • 54
  • 94