将结果集保存为字符串

saving resultset to String

我正在学习 MySQL 和 Java,并且我正在尝试创建一个方法来获取数据库中的当前字符串并将其更改为其他字符串。

我的代码如下所示:

public void changeStatus(int taskID) throws SQLException 
{
    try {
        // 1. Get a connection to database
        myConn = DriverManager.getConnection(dbUrl, dbUser, dbPass);

        // 2. Create a statement
        myStmt = myConn.prepareStatement("select 'status' from tasks where id=?");

        myStmt.setInt(1, taskID);

        myRs = myStmt.executeQuery();
        String statusString = myRs.getString("status");


        if (statusString != null)
        {
            myStmt = myConn.prepareStatement("update tasks set status=? where id=?");
            if (statusString.equals("New"))
            {
                myStmt.setString(1, "In Process");
                myStmt.setInt(2, taskID);
                myStmt.executeUpdate();
            }
            else if (statusString.equals("In Process"))
            {
                myStmt.setString(1, "Done");
                myStmt.setInt(2, taskID);
                myStmt.executeUpdate();
            }
            else if (statusString.equals("Done"))
            {
                myStmt.setString(1, "New");
                myStmt.setInt(2, taskID);
                myStmt.executeUpdate();
            }
        }
    }
    catch (Exception exc) {
        exc.printStackTrace();
    }
    finally {
        if (myRs != null) {
            myRs.close();
        }

        if (myStmt != null) {
            myStmt.close();
        }

        if (myConn != null) {
            myConn.close();
        }
    }
}

它说我得到 java.sql.SQLException: 在结果集开始之前。 我认为问题出在这一行:

             String statusString = myRs.getString("status");

我需要更改什么才能使其正常工作?

取值前必须将光标移动到下一个位置。

myRs.next();
String statusString = myRs.getString("status");

来自docs

You access the data in a ResultSet object through a cursor. Note that this cursor is not a database cursor. This cursor is a pointer that points to one row of data in the ResultSet object. Initially, the cursor is positioned before the first row. You call various methods defined in the ResultSet object to move the cursor.

在读取结果集之前必须调用 myRs.next()

或者最好先检查结果集中是否有条目:

if (myRs.hasNext()){
  myRs.next()
  String statusString = myRs.getString("status");
}

你的查询还有一个问题:

myStmt = myConn.prepareStatement("select 'status' from tasks where id=?");

您必须删除列名 status 周围的单引号。必须是:

 myStmt = myConn.prepareStatement("select status from tasks where id=?");