java - Spring mvc - jsp MySQLSyntaxErrorException

标签 java mysql jsp spring-mvc

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

我的 Controller 中有以下功能:

@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字符串有问题吗?

最佳答案

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

一定是

resultSet = ps.executeQuery();

请参阅Javadoc来自方法executeQuery(String sql):

Note:This method cannot be called on a PreparedStatement or CallableStatement

同时删除语句末尾的 ;:

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

关于java - Spring mvc - jsp MySQLSyntaxErrorException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31810083/

相关文章:

java - 如何保护用户页面免受暴力攻击

java - 如何获取jar类来自

java - org.ksoap2.serialization.SoapObject 无法转换为 org.ksoap2.serialization.SoapPrimitive

java - 在Java中修改文件的特定行

mysql - 我应该为 Spring 3.1.0、Hibernate 4.0.1.Final 和 MySQL 5.1 使用什么合并数据源?

mysql - 使用 Closure Table 的 SQL 家谱谱系,支持配偶、 sibling 、姻亲、 sibling 等

java - struts逻辑标签呈现html格式,JSTL标签不

java - 将 JavaObject `scala.collection.Map<Object,RDD<?>>` 转换为 python 字典

javascript - 从 MySQL 加载数据到 Highchart 并以适当的方式显示

java - liferay - 无法调用Portlet类的processAction