我想创建一个简单的程序,它连接到数据库。 我不知道是什么问题。
这里是我的代码:
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
在库中。