需要帮助使用数据源连接池连接到数据库(Need help on connecting to data

2019-09-27 04:28发布

我想创建一个简单的程序,它连接到数据库。 我不知道是什么问题。

这里是我的代码:

Products.java / getter和setter * /


ProductsDao.java

public class ProductsDao {

    public ArrayList getAllProducts() throws NamingException, SQLException{
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        conn = ConnectionFactory.getConnection();
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT * FROM products");
        ArrayList products = new ArrayList();

        while(rs.next()){
            Products product = new Products();
            product.setId(rs.getInt("id"));
            products.add(product);
        }

        return products;
    }

}


的context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/grocerific">
    <Resource 
    auth="Container"
    driverClassname="com.mysql.jdbc.Driver"
    name="/pool/grocerific"
    maxActive="100"
    maxIdle="30"
    maxWait="1000"
    type="javax.sql.DataSource"
    url="jdbc:mysql://localhost:3306/grocerific"
    username="root"
    password="secret"
    />
</Context>

ConnectionFactory.java

    public static Connection getConnection() throws NamingException, SQLException{
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/grocerific");
        Connection conn = ds.getConnection();
        return conn;
    }

 GetProductsServlet.java

  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, NamingException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();


    try {
        /* TODO output your page here. You may use following sample code. */
        ProductsDao productsDao = new ProductsDao();
        ArrayList products = productsDao.getAllProducts();
        out.println(products);
    } finally {            
        out.println("error!");
    }
}

我也从配置服务,扩大数据库节点,并创建一个新的连接。 我测试了它,并说,这是成功的。 我还添加了库mysql-jdbc-connector.zip在库中。

Answer 1:

我看到一个context.xml的,所以我假定这是要在Tomcat上运行(非常有用的信息,让您知道)。

Tomcat的需要你也把到数据源中的条目在web.xml - Tomcat文档解释了所有这很清楚。

http://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html



文章来源: Need help on connecting to database using datasource connection pool