gpt4 book ai didi

java - ResultSet 方法 previous() 不起作用

转载 作者:行者123 更新时间:2023-12-01 07:03:26 24 4
gpt4 key购买 nike

   public void actionPerformed(ActionEvent E)
{
int id;
String name,address,phone;
Connection conn = null;
PreparedStatement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query
String sql;
sql = "SELECT * FROM person";
System.out.println("Creating statement...");
stmt = conn.prepareStatement (sql,ResultSet.TYPE_SCROLL_INSENSITIVE ,
ResultSet.CONCUR_UPDATABLE );


ResultSet rs = stmt.executeQuery(sql);

if(E.getSource()== bNext) {
rs.next();
id = rs.getInt("id");
name = rs.getString("name");
address = rs.getString("address");
phone = rs.getString("phone");

//Display values
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.print(", Address: " + address);
System.out.println(", Phone: " + phone);
}
if(E.getSource()== bPrevious) {
rs.previous();
id = rs.getInt("id");
name = rs.getString("name");
address = rs.getString("address");
phone = rs.getString("phone");

//Display values
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.print(", Address: " + address);
System.out.println(", Phone: " + phone);
}
if(E.getSource()==bLast) {
rs.last();
id = rs.getInt("id");
name = rs.getString("name");
address = rs.getString("address");
phone = rs.getString("phone");

//Display values
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.print(", Address: " + address);
System.out.println(", Phone: " + phone);
}
if(E.getSource()==bFirst) {
rs.first();
id = rs.getInt("id");
name = rs.getString("name");
address = rs.getString("address");
phone = rs.getString("phone");

//Display values
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.print(", Address: " + address);
System.out.println(", Phone: " + phone);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}

我不知道为什么,但是 previous() 方法不起作用,每当用户按下 next 按钮时,输出都保持不变,并且不会向前移动。有人可以帮忙吗?

最佳答案

每次调用 actionPerformed 方法时(我假设按下某个按钮时会调用它),您都会再次执行查询。因此 next() 将始终为您提供第一个元素,而 previous 将返回 false。

您可能应该将所有行读入某些数据结构,例如ArrayList(作为初始化步骤,而不是在单击按钮时),并维护该List<的当前索引,这将允许您在单击按钮时向前或向后移动。

附注在不检查返回值的情况下,不应使用 rs.next() 或 rs.previous() 。如果这些方法返回 false,则不应调用 rs.getInt("id") 等方法,因为它们会引发异常。

P.P.S 一些 JDBC 驱动程序不支持 previous()firstlast 方法,这意味着它们可能会抛出 SQLFeatureNotSupportedException。但是,如果您按照我的建议在初始化步骤中读取了所有数据,则只需要 next()

关于java - ResultSet 方法 previous() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556118/

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