JSP(Java Server Pages)是一种动态网页技术,它允许在HTML或XML文档中直接嵌入Java代码片段和表达式。这些代码在服务器上执行后生成动态内容,然后发送到客户端浏览器。
MySQL是一个流行的关系型数据库管理系统(RDBMS),它使用结构化查询语言(SQL)进行数据操作和管理。
以下是一个简单的JSP页面示例,它连接到MySQL数据库并执行一个查询:
<%@ page import="java.sql.*" %>
<html>
<head>
<title>MySQL Connection Example</title>
</head>
<body>
<h1>MySQL Connection Example</h1>
<%
try {
// 加载JDBC驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
// 建立数据库连接
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "myuser";
String password = "mypassword";
Connection conn = DriverManager.getConnection(url, username, password);
// 执行SQL查询
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
// 处理查询结果
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
out.println("Name: " + name + ", Age: " + age + "<br>");
}
// 关闭资源
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
out.println("JDBC驱动程序未找到!");
} catch (SQLException e) {
out.println("数据库连接或查询出错:" + e.getMessage());
}
%>
</body>
</html>
注意:在实际应用中,请确保将上述代码中的数据库URL、用户名和密码替换为实际的值,并处理可能的异常情况。
领取专属 10元无门槛券
手把手带您无忧上云