【问题标题】:Spring mvc - jsp MySQLSyntaxErrorExceptionSpring mvc - jsp MySQLSyntaxErrorException
【发布时间】:2015-08-04 13:01:00
【问题描述】:

我正在尝试从 MYSQL DB 中捕获参数并通过 spring mvc 将其打印在 JSP 页面上。

我的控制器中有以下功能:

@RequestMapping(value = "/showentry")
public ModelAndView showentry(@RequestParam("id") String id){
    System.out.println("xxxxxxxxxxxxxxxxxxxxxxxx" + id);
    entries = dao.search(id);
    ModelAndView mav = new ModelAndView();
    mav.addObject("list", entries);
    return mav;
}

从以下形式获取参数“Id”:

  <form action="showentry">
    <input type=  "hidden" name="id" value = "${item.id}">
    <button> Show Entry </button>
  </form>

调用showentry方法的函数在DAO类中:

@Override
public List<Entry> search(String id) {
    List<Entry> res = new ArrayList<Entry>();
    String sql = "SELECT * FROM Person WHERE Id = ? ;";
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet resultSet = null;
    try {
        //open connection
        conn = dataSource.getConnection();

        //prepare the statement
        ps = conn.prepareStatement(sql);

        //bind parameters to preparedstatement
        ps.setString(1, id);

        //execute the statement
        resultSet = ps.executeQuery(sql);

        while (resultSet.next()) {
            Entry entry = new Entry();
            entry.setId(resultSet.getInt("id"));
            entry.setCn(resultSet.getString("cn"));
            entry.setSn(resultSet.getString("sn"));
            entry.setPn(resultSet.getString("pn"));
            res.add(entry);
        }
    } catch (SQLException ex) {
        //[...]
    }
    return res;
}

我可以在日志上打印带有与条目相关的 id 的字符串,例如: xxxxxxxxxxxxxxxxxxxxxxxx 32

但是在jsp上不打印,并且返回错误:

net.tirasa.springaddressbook.SpringEntryDAO search
GRAVE: null
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 '?' at line 1

sql 字符串有问题吗?

【问题讨论】:

    标签: java mysql jsp spring-mvc


    【解决方案1】:

    你必须删除resultSet = ps.executeQuery(sql);中的参数

    一定是

    resultSet = ps.executeQuery();
    

    从方法executeQuery(String sql)中查看Javadoc

    注意:此方法不能在 PreparedStatement 或 可调用语句

    同时删除语句末尾的;

    String sql = "SELECT * FROM Person WHERE Id = ?";
    

    【讨论】:

      【解决方案2】:

      您是否尝试过删除 sql 中的分号

      String sql = "SELECT * FROM Person WHERE Id = ? ;";

      【讨论】:

        猜你喜欢
        • 2014-08-05
        • 1970-01-01
        • 2014-12-05
        • 2013-09-25
        • 2015-12-07
        • 1970-01-01
        • 1970-01-01
        • 2011-10-27
        • 1970-01-01
        相关资源
        最近更新 更多