Need help on connecting to database using datasource connection pool

核能气质少年 提交于 2020-01-05 04:03:10

问题


I'd like to create a simple program where it connects to a database. I don't know what the problem is.

Here is my code:

Products.java /getters and setters*/


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

I have also configured services from and expanded the database node and create a new connection. I tested it, and says it was successful. I've also added the library mysql-jdbc-connector.zip in libraries.


回答1:


I see a context.xml, so I'm assuming this is to be run on Tomcat (quite useful information to give you know).

Tomcat requires you to also put an entry to the datasource in your web.xml - the Tomcat documentation explains all that quite clearly.

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



来源:https://stackoverflow.com/questions/13622464/need-help-on-connecting-to-database-using-datasource-connection-pool

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!