2017-05-29 52 views
-1

我在Java代碼下運行時遇到問題。我找不到DB.java類。從數據庫讀表

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")); 
} 

我正在使用Glassfish服務器。有人可以幫我寫DB.java課嗎?

+0

你應該和發佈錯誤消息 – Irfan

+0

更好可否請您添加的目的DB.java文件。你想實現連接池嗎?或者只是創建並返回新的連接? 發佈答案取決於您的期望。 –

回答

0

getConnection()方法是DriverManager類的一部分。正確初始化DriverManager的,因爲在這個職位描述:

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

示例代碼以供將來參考:

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