05. JDBC 在Servlet中的应用

本文介绍如何使用JDBC在Servlet中与数据库交互,并通过示例演示了配置数据库连接参数的方法,以及如何将查询结果转发给JSP生成响应。

JDBC 在 Servlet 中的应用,用法基本等同于在Java SE中的应用;
一般来说实际与数据库交互使用Servlet来处理,之后将结果集转发给JSP生成响应,对于数据库的连接参数,可以储存在一个类中,方便多个Model进行调用,同时方便数据库连接参数的修改;

以下一个简单的示例:

DataAccessConfig.java:储存数据库连接参数,可以将该类实现为一个工厂类,以便分为各套连接参数的灵活调用;
public class DataAccessConfig{
    private String dirver = "com.mysql.jdbc.Driver";
    private String url = "jdbc:mysql//localhost/demo";
    private String user = "root";
    priavte String password = "123";
    public String getDriver(){ retrun this.driver};
    public String getUrl(){ retrun this.Url};
    public String getUser(){ retrun this.user};
    public String getPassword(){ retrun this.password};
}
DataAccess.java:处理数据库逻辑的Model Servlet
@WebServlet("/DatabaseAccess")
public class DatabaseAccess extends HttpServlet {
    private DataAccessConfig config = null;
    public DataAccess(){
        super();
        config = new DataAccessConfig();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        Connection connection = null;
	    try{
            //执行数据库查询操作
            Class.forName(config.getDriver());
            connection = DriverManager.getConnection(config.getUrl(),config.getUser(),config.getPassword());
            Statement statement = conncection.createStatement();
            Resulset resultset = statement.executeQuery("select isbn,author,title,price from books");
            //将结果集转发到一个JSP页面生成响应页
            request.setAttribute("resultset",resultset);
            getServletContext().getRequestDispatcher("/showResultSet.jsp").forward(request,response);
            
            
        }catch(SQLException ex){
            getServletContext.log("SQLException",ex)
        }catch(Exception ex){
            getServletContext.log("Other Exception",ex)
        }finally{
            connection.close();
        }
    }
        
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
showResultSet.jsp  :显示数据库结果集

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%! ResultSet resultset = request.getAttribute("resultset"); %>    
<html>
<head><title>result set</title></head>
<body>
<% while(resultset.next()){ %>
    <p><%= resultset.getString("isbn")%> | 
       <%= resultset.getString("author")%> | 
       <%= resultset.getString("title")%> | 
       <%= resultset.getFloat("price")%> 
    </p>
<% } %>
</body>
</html>


HTTP Status 500 - javax.servlet.ServletException: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc' at line 1 type Exception report message javax.servlet.ServletException: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc' at line 1 description The server encountered an internal error that prevented it from fulfilling this request. exception org.apache.jasper.JasperException: javax.servlet.ServletException: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc' at line 1 org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:560) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:461) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) root cause javax.servlet.ServletException: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc' at line 1 org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:909) org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:838) org.apache.jsp.index_jsp._jspService(index_jsp.java:248) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) root cause com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc' at line 1 sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) java.lang.reflect.Constructor.newInstance(Constructor.java:423) com.mysql.jdbc.Util.handleNewInstance(Util.java:425) com.mysql.jdbc.Util.getInstance(Util.java:408) com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944) com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2480) com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2438) com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1381) dbtaobao.connDb.index(connDb.java:45) org.apache.jsp.index_jsp._jspService(index_jsp.java:115) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) note The full stack trace of the root cause is available in the Apache Tomcat/8.0.41 logs.
最新发布
06-30
在Java Web应用中,JSP页面因MySQL SQL语法错误导致的HTTP 500异常通常与后端数据库操作相关。`javax.servlet.ServletException` 是一个通用的Servlet异常类,而 `MySQLSyntaxErrorException` 则是其子类,表示SQL语句存在语法问题[^1]。 当发生此类异常时,控制台或日志文件中可能会显示类似 `desc line 1` 的信息,这表明SQL查询解析失败,并且问题可能出现在表结构定义、关键字使用不当或查询拼接逻辑错误等方面。 ### 常见原因及排查方法 #### 1. SQL语法错误 - **关键词拼写错误**:例如误将 `SELECT` 写成 `SELEC`。 - **字段名或表名错误**:字段名或表名不存在或大小写不一致(特别是在Linux环境下)。 - **缺少逗号或括号不匹配**:在构建复杂查询时容易出现这类问题。 ```java String query = "SELECT id, name FROM users WHERE username = '" + username + "' AND password = '" + password + "'"; ``` 如果变量 `username` 或 `password` 包含特殊字符(如单引号),则会导致SQL注入风险或语法错误。建议使用预编译语句来避免此类问题: ```java String query = "SELECT id, name FROM users WHERE username = ? AND password = ?"; PreparedStatement stmt = connection.prepareStatement(query); stmt.setString(1, username); stmt.setString(2, password); ResultSet rs = stmt.executeQuery(); ``` #### 2. 表结构定义问题 - **字段类型不匹配**:例如试图将字符串插入到整数类型的列中。 - **约束违反**:唯一性约束、外键约束等未满足条件。 检查数据库表结构是否与代码中的预期一致,可以使用以下命令查看表结构: ```sql DESCRIBE users; ``` #### 3. 日志分析与调试技巧 - **启用详细的日志记录**:确保应用服务器(如Tomcat)和数据库驱动程序的日志级别设置为DEBUG或TRACE,以便捕获完整的错误堆栈信息。 - **使用try-catch块捕获异常并打印详细信息**: ```java try { // 数据库操作代码 } catch (SQLException e) { e.printStackTrace(); } ``` #### 4. 配置与部署问题 - **数据库连接配置错误**:确保 `web.xml` 或 `context.xml` 中的JNDI配置正确无误。 - **驱动版本不兼容**:确认使用的JDBC驱动版本与MySQL服务器版本兼容。 --- ### 示例:处理SQL语法错误的完整代码片段 以下是一个简单的JSP页面示例,展示如何安全地执行SQL查询并处理潜在的语法错误: ```jsp <%@ page import="java.sql.*" %> <% String url = "jdbc:mysql://localhost:3306/mydb"; String user = "root"; String password = "password"; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(url, user, password); String query = "SELECT * FROM users WHERE id = ?"; stmt = conn.prepareStatement(query); stmt.setInt(1, Integer.parseInt(request.getParameter("id"))); rs = stmt.executeQuery(); while (rs.next()) { out.println("User ID: " + rs.getInt("id") + ", Name: " + rs.getString("name") + "<br>"); } } catch (ClassNotFoundException | SQLException e) { out.println("Database error: " + e.getMessage()); e.printStackTrace(); } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } %> ``` --- ### 总结 处理由SQL语法错误引起的 `MySQLSyntaxErrorException` 需要从多个角度入手,包括检查SQL语句本身、验证数据输入、审查数据库结构以及增强异常处理机制。通过上述方法,能够有效定位并修复问题,从而避免HTTP 500错误的发生。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值