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