在setAttribute()之后设置name属性的值会中断

时间:2014-08-21 08:24:42

标签: java jdbc

我想创建一个name属性并使用resultset方法为其设置一个值,但它会在request.setAttribute(..)之后中断。

退出第一个if else结构,但不进行转发或返回语句。

如果我使用rs.next()作为名称的值,则效果非常好,所以我非常确定我使用rs.getString的方式是错误的。我检查了文档,找不到我的错误。

String sql = "select * from students where id="+ request.getParameter("st_id");
ResultSet rs= stmt.executeQuery(sql);

if (rs.wasNull()) {
    request.getRequestDispatcher("/login_fail.jsp").forward(request, response);
    return; 
}else{
    request.setAttribute("name", rs.getString("name"));
    request.getRequestDispatcher("/login_action.jsp").forward(request, response);
    return; 
}

3 个答案:

答案 0 :(得分:0)

您可以尝试更改查询并提供以下列名称:

String sql = "select name, col1 from students where id="+ request.getParameter("st_id");
ResultSet rs= stmt.executeQuery(sql);

然后你可以像这样使用rs.getstring:

if(rs.next())
{
if (rs.wasNull()) 
{
    request.getRequestDispatcher("/login_fail.jsp").forward(request, response);
    return;
}
else
{
    request.setAttribute("name", rs.getString(1));
    request.getRequestDispatcher("/login_action.jsp").forward(request, response);
    return;
}
}

答案 1 :(得分:0)

你应该致电rs.next()。因为当您收到ResultSet时,光标指向结果集第一行之前的位置。因此,您必须调用next()方法然后获取结果 在java API中它说

boolean next() throws SQLException

Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

Read documentation on ResultSet.next()

所以你可以编码如下

String sql = "select * from students where id="+ request.getParameter("st_id");
ResultSet rs= stmt.executeQuery(sql);

if(rs.next()){
    if (rs.wasNull()) {
        request.getRequestDispatcher("/login_fail.jsp").forward(request, response);
    }else{
        request.setAttribute("name", rs.getString("name"));
        request.getRequestDispatcher("/login_action.jsp").forward(request, response);
    }
}

答案 2 :(得分:0)

请在此处打印列名。

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();

// The column count starts from 1
for (int i = 1; i < columnCount + 1; i++ ) {
  String name = rsmd.getColumnName(i);
   System.out.println(name);
}

尝试更改以下代码

String sql = "select * from students where id="+ request.getParameter("st_id");
            ResultSet rs= stmt.executeQuery(sql);


            if (rs.wasNull()) {
                request.getRequestDispatcher("/login_fail.jsp").forward(request, response);
                return; 
            }else{
              while (resultSet.next()) {
                request.setAttribute("name", rs.getString("name"));
                request.getRequestDispatcher("/login_action.jsp").forward(request, response);
                }
            return; 
            }