0

当我尝试使用 Datasource 对象连接到我的数据库时,我遇到了这个烦人的 Noclassdeffounderror。

我的代码:

 package Main;

import java.sql.Connection;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.commons.dbcp.BasicDataSource;


public class DBConnection {

Connection connection = null;

BasicDataSource bdSource = new BasicDataSource();


public DBConnection(){

    bdSource.setDriverClassName("com.mysql.jdbc.Driver");
    bdSource.setUrl("jdbc:mysql://localhost:3306/sandwichdeluxe");
    bdSource.setUsername("root");
    bdSource.setPassword("killer");


}

 public Connection createConnection() {
     Connection con = null;
     try {
             if (connection != null) {
                     System.out.println("Cant create a New Connection");
             } else {
                     con = bdSource.getConnection();
                     System.out.println("Connection Done successfully");
             }
     } catch (Exception e) {
             System.out.println("Error Occured " + e.toString());
     }
     return con;
 }

 public static void main(String args[]) throws Exception {
     DBConnection dsExample = new DBConnection();
     Connection con = dsExample.createConnection();
     Statement stmt = con.createStatement();
     String query = "SELECT * FROM biryani";
     ResultSet rs = stmt.executeQuery(query);
     while (rs.next()) {
             System.out.println("ID- " + rs.getString("id") + ", Name- "
                             + rs.getInt("name") + ", Price- "
                             + rs.getString("price") + ", Details- "
                             + rs.getString("details") + ", Strengt +  

 rs.getString("strength"));
     }
     con.close();
     stmt.close();
     rs.close();
 }
}

堆栈跟踪:

 Exception in thread "main" java.lang.NoClassDefFoundError:         
 org/apache/commons/pool/ObjectPool
at Main.DBConnection.<init>(DBConnection.java:15)
at Main.DBConnection.main(DBConnection.java:44)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool.ObjectPool
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 2 more

我在我的项目库中添加了 jar: 1. mysql-connector-java-5.1.18-bin.jar 2. commons-dbcp-1.4.jar (这是用于数据源)

4

1 回答 1

0

您在类路径中缺少ObjectPool该类。此类由 Apache 的 Commons Pools 库提供,您可以在此处找到。

于 2013-11-08T14:28:45.723 回答