简体   繁体   English

PreparedStatement,用于读取临时参数

[英]PreparedStatement for reading temporary parameter

I am trying to read a temporary variable created from my MySql query as follows: 我试图读取从MySql查询创建的临时变量,如下所示:

String name = "";
                            selectQuery = "select (select "
                                    + "CONCAT(s.firstname,\" \",s.surname) "
                                    + "AS name) "
                                    + "from student s, marks m where m.grade = 'fail'";
                            try{
                                pstmt = con.prepareStatement(selectQuery);

                                rs = pstmt.executeQuery(selectQuery);
                                int count = 0;

                                while(rs.next()){
                                    name = rs.getString("name");
                                    System.out.println(++count+". "+name);
                                }
                                rs.close();
                                pstmt.close();
                            }catch(Exception e){
                                e.printStackTrace();
                            }

I get SQLException as column 'name' not found. 由于找不到列“名称”,我得到了SQLException。 When I run the query in MySql server it runs fine. 当我在MySql服务器中运行查询时,它运行良好。

In order for the alias to apply, it must be places outside the nested query's parenthesis, not inside it. 为了应用别名,别名必须位于嵌套查询括号的外部 ,而不是内部。 However, you could just drop it altogether and just use the concat call directly in the select list. 但是,您可以将其完全删除,而直接在选择列表中使用concat调用。

Two more side notes: 另外两个注意事项:

  1. Implicit joins (ie, placing more than one table in the from list) have been deprecated for quite a while. 隐式联接(即,在from列表中放置多个表)已经被淘汰了一段时间。 It's considered a better practice to use explicit joins. 使用显式联接被认为是更好的做法。
  2. Regardless of the joining syntax you're using, you're missing the join condition. 无论使用哪种连接语法,都缺少连接条件。
  3. Using concat_ws instead of concat may save you some hassle with handling the white space yourself. 使用concat_ws代替concat可能会为您节省一些处理空白的麻烦。

To make a long story short: 使长话短说:

select CONCAT_WS(' ', s.firstname, s.surname) AS name
FROM   student s
JOIN   marks m ON s.id = m.student_id
WHERE  m.grade = 'fail'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM