JSP(Java Server Pages)是一种动态网页技术,它允许在HTML或XML文档中直接嵌入Java代码片段和表达式。通过JSP,开发者可以轻松地创建动态网页,并与数据库进行交互。
JSP直接访问数据库主要涉及以下几种类型:
JSP直接访问数据库广泛应用于各种Web应用中,例如:
原因:
解决方法:
<%@ page import="java.sql.*" %>
<%
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
out.println("数据库连接成功!");
} catch (ClassNotFoundException e) {
out.println("JDBC驱动加载失败:" + e.getMessage());
} catch (SQLException e) {
out.println("数据库连接失败:" + e.getMessage());
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
原因:
解决方法:
<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
if (rs.next()) {
out.println("登录成功!");
} else {
out.println("用户名或密码错误!");
}
} catch (ClassNotFoundException e) {
out.println("JDBC驱动加载失败:" + e.getMessage());
} catch (SQLException e) {
out.println("数据库操作失败:" + e.getMessage());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
领取专属 10元无门槛券
手把手带您无忧上云