如您所见,此代码是我的数据访问对象层的一部分。我以前从未使用过 ConnectionPool 对象,因为我还在学习 Java。无论如何,我收到一条错误消息,说明:
对于 ConnectionPool 类型,方法 getInstance() 未定义。(第 5 行)
如果你们中的任何人以前经历过这种情况,我们将不胜感激。
import java.sql.*;
import java.util.*;
import org.apache.tomcat.jdbc.pool.ConnectionPool;
import music.business.*;
public class ProductDB
{
//This method returns null if a product isn't found.
public static Product selectProduct(String productCode)
{
ConnectionPool pool = ConnectionPool.getInstance(); //<===<====<====<=================
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT * FROM Product " +
"WHERE ProductCode = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, productCode);
rs = ps.executeQuery();
if (rs.next())
{
Product p = new Product();
p.setCode(rs.getString("ProductCode"));
p.setDescription(rs.getString("ProductDescription"));
p.setPrice(rs.getDouble("ProductPrice"));
return p;
}
else
{
return null;
}
}
catch(SQLException e)
{
e.printStackTrace();
return null;
}
finally
{
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
我刚刚发现我犯了一个错误: - 我上面提到的类中的 ConnectionPool 不应该是 Tomcat 导入的。它是一个 JNDI 类。见下文。getInstance 实际上是我的 JNDI 类中的一个方法。抱歉耽误你们的时间了伙计们。谢谢
import java.sql.*;
import javax.sql.DataSource;
import javax.naming.InitialContext;
public class ConnectionPool
{
private static ConnectionPool pool = null;
private static DataSource dataSource = null;
public synchronized static ConnectionPool getInstance()
{
if (pool == null)
{
pool = new ConnectionPool();
}
return pool;
}
private ConnectionPool()
{
try
{
InitialContext ic = new InitialContext();
dataSource = (DataSource) ic.lookup("java:/comp/env/jdbc/musicDB");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public Connection getConnection()
{
try
{
return dataSource.getConnection();
}
catch (SQLException sqle)
{
sqle.printStackTrace();
return null;
}
}
public void freeConnection(Connection c)
{
try
{
c.close();
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
}
}