gpt4 book ai didi

java - 将结果集保存为字符串

转载 作者:行者123 更新时间:2023-11-29 00:01:37 27 4
gpt4 key购买 nike

我正在学习 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: Before start of result set。我认为问题出在这一行:

             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.

关于java - 将结果集保存为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29537480/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com