JSP (JavaServer Pages) 是一种用于创建动态网页的技术,它允许在HTML页面中嵌入Java代码。JSP页面在服务器端执行,生成HTML页面并发送给客户端。
MySQL 是一种流行的关系型数据库管理系统(RDBMS),广泛用于Web应用程序的数据存储。
类型:
应用场景:
以下是一个简单的JSP页面示例,展示如何将数据插入到MySQL数据库中:
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Add Data to MySQL</title>
</head>
<body>
<h2>Add New Record</h2>
<form action="addData.jsp" method="post">
Name: <input type="text" name="name"><br><br>
Email: <input type="text" name="email"><br><br>
<input type="submit" value="Add Record">
</form>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
if (name != null && email != null) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Connect to the database
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";
conn = DriverManager.getConnection(url, user, password);
// Prepare the SQL statement
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, email);
// Execute the SQL statement
int rowsInserted = pstmt.executeUpdate();
if (rowsInserted > 0) {
out.println("A new record was inserted successfully!");
}
} catch (Exception e) {
out.println("Error: " + e.getMessage());
} finally {
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
out.println("Error closing resources: " + e.getMessage());
}
}
}
%>
</body>
</html>
问题1:数据库连接失败
问题2:SQL语句执行错误
问题3:资源未正确关闭
finally
块确保所有资源在异常情况下也能被正确关闭。通过以上步骤和示例代码,你应该能够成功地将数据从JSP页面插入到MySQL数据库中。如果有更多具体问题,欢迎进一步咨询。
领取专属 10元无门槛券
手把手带您无忧上云