我想创建一个连接数据库的简单程序。我不知道问题是什么。
这是我的代码:
Products.java / getter 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!");
}
}
我还从数据库节点配置服务并扩展了数据库节点并创建了新连接。我测试了它,并说它很成功。我还在库中添加了库mysql-jdbc-connector.zip
。
答案 0 :(得分:0)
我看到了一个context.xml,所以我假设这是在Tomcat上运行的(非常有用的信息可以让你知道)。
Tomcat要求您还在web.xml中的数据源中添加一个条目 - Tomcat文档非常清楚地解释了这一点。
http://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html