1

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

这是我的代码:

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

}


上下文.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库。

4

1 回答 1

0

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

Tomcat 还要求您在 web.xml 中为数据源添加一个条目 - Tomcat 文档非常清楚地解释了所有这些。

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

于 2012-11-29T09:41:47.870 回答