在Java中,我们可以使用JDBC(Java Database Connectivity)或者JPA(Java Persistence API)来实现对数据库的操作,以下是一个简单的示例:
我们需要创建一个连接数据库的工具类:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
private static final String URL = "jdbc:mysql://localhost:3306/myDB";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
```
我们可以在Servlet中使用这个工具类来查询数据库:
```java
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String searchWord = req.getParameter("search_word");
Listtry {
Connection conn = DBUtil.getConnection();
String sql = "SELECT * FROM products WHERE name LIKE ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "%" + searchWord + "%");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
results.add("id: " + rs.getInt("id") + " - Name: " + rs.getString("name") + " - Price: " + rs.getDouble("price"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 这里可以添加关闭数据库连接的代码,如果需要的话。
}
req.setAttribute("results", results);
req.getRequestDispatcher("/result.jsp").forward(req, resp);
}
```
我们可以在JSP页面上显示查询结果:
```jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>产品搜索结果
- <% for (String result : results) { %>
- <%= result %> <% } %>
```
还没有评论,来说两句吧...