How to retrieve data from a database to a page using JSP?
To retrieve data from the database and display it on a JSP page, you need to follow these steps:
First, make sure you are connected to the database. You can use JDBC (Java Database Connectivity) to establish the database connection.
In a JSP page, use `<%@ page import="java.sql.*" %>` to import the `java.sql` package, so that the relevant database classes and interfaces can be used on the page.
3. In a JSP page, establish a connection with the database by creating a `Connection` object.
<%Connection conn = null;
try {
// 加载数据库驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
String url = "jdbc:mysql://localhost:3306/your_database_name";
String username = "your_username";
String password = "your_password";
conn = DriverManager.getConnection(url, username, password);
} catch(ClassNotFoundException e) {
e.printStackTrace();
} catch(SQLException e) {
e.printStackTrace();
}
%>
Please make sure to replace `your_database_name` with the name of your database, and provide the correct username and password.
4. Create a `Statement` object to execute SQL query statements, such as:
<%Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
String sql = "SELECT * FROM your_table_name";
rs = stmt.executeQuery(sql);
// 处理结果集
while(rs.next()) {
// 读取每一行数据并输出到页面上
out.println(rs.getString("column_name"));
}
} catch(SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
try {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(conn != null) conn.close();
} catch(SQLException e) {
e.printStackTrace();
}
}
%>
Please make sure to replace `your_table_name` with your table name, and modify column names as needed.
Finally, you can use JSP tags and syntax to design the layout of the page in order to display the data retrieved from the database. For example:
<!DOCTYPE html><html>
<head>
<title>数据库数据显示</title>
</head>
<body>
<%-- 数据显示部分 --%>
<h1>数据库数据</h1>
<ul>
<%
while(rs.next()) {
%><li><%=rs.getString("column_name")%></li><%
}
%>
</ul>
</body>
</html>
It is important to remember to handle exception cases and promptly close database connections when dealing with database connections and executing SQL queries.